首页 > 解决方案 > Micronaut - @Controller 与 @Endpoint

问题描述

我不明白何时应该使用@Controller以及何时@Endpoint使用 Micronaut 框架创建端点。

按照文档,我创建了一个服务并以/endpoint这种方式使其可用:

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

这里它是用@Endpoint注释创建的:

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

在 Micronaut 的端点上创建服务并使其可用的正确方法是什么?
如果这个问题是由于对更基本的概念缺乏理解而引起的,你能给我提供参考吗?

标签: javamicroservicesendpointmicronaut

解决方案


@Endpoint应该用于管理端点(调整日志级别、管理缓存、监控资源利用率等),而不是应用程序功能。 @Controller应该用于不属于管理和监控的应用程序端点。

编辑

为了解决具体提出的问题:

在 Micronaut 的端点上创建服务并使其可用的正确方法是什么?

通常,这样做的方法是将 bean 添加到作为您的服务的应用程序上下文中,然后让 DI 容器在需要的地方注入该 bean。

@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;
    }

    // ...
}

推荐阅读