Search code examples
javamicroservicesendpointmicronaut

Micronaut - @Controller vs @Endpoint


I don't understand when I should use @Controller and when @Endpoint to create an endpoint with Micronaut framework.

Following the documentation I created a service and made it available at /endpoint this way:

@Controller("/endpoint") 
public class DummyService {
    @Get 
    @Produces(MediaType.TEXT_PLAIN) 
    public String index() {
        return "Hello World!"; 
    }
}

But here it's created with the @Endpoint annotation instead:

@Endpoint("/endpoint") 
public class DummyService {
    @Get 
    @Produces(MediaType.TEXT_PLAIN) 
    public String index() {
        return "Hello World!"; 
    }
}

Which is the proper way to create a service and make it available at an endpoint in Micronaut?
If this question arises from a lack of understanding of more basic concepts, could you provide me with references?


Solution

  • @Endpoint is supposed to be used for management endpoints (adjusting log levels, managing caches, monitoring resource utilization, etc), not application functionality. @Controller should be used for application endpoints that are not part of management and monitoring.

    EDIT

    To address the question specifically asked:

    Which is the proper way to create a service and make it available at an endpoint in Micronaut?

    In general, the way to do that is to add a bean to the application context that is your service, and then let the DI container inject that bean wherever is needed.

    @Singleton
    public class SomeService {
        // ...
    }
    
    @Controller
    public class SomeController {
        private final SomeService someService;
    
        public SomeController(SomeService someService) {
            this.someService = someService;
        }
    
        // ...
    }
    
    @Endpoint
    public class SomeManagementEndpoint {
        private final SomeService someService;
    
        public SomeManagementEndpoint(SomeService someService) {
            this.someService = someService;
        }
    
        // ...
    }