繁体   English   中英

SpringBoot获取应用的@RestController列表即List<@RestController>

[英]SpringBoot get the list of @RestController i.e List<@RestController> of the application

关于 SpringBoot 应用程序的小问题,以及如何获取用@RestController注释的类列表。

我有一个简单的 SpringBoot 应用程序,其中有几个我自己的@RestController ,例如:

@RestController
public class PersonController {

@RestController
public class OrderController {

@RestController
public class PriceController {

但是我也有我的依赖项,在我无法控制的第三方库中,还有一些@RestController

在我的应用程序中,我想获取所有@RestController的列表,即所有用注释@RestController注释的类。 类似List<@RestController>的东西,请注意 @ 符号,它不是List<RestController>

到目前为止,我尝试的是使用通用接口扩展我的所有@RestController ,并获取List<MyAtRestController> ,但此解决方案将仅限于我可以控制的@RestController 许多都在第三方依赖项中。

问题,请问如何从 SpringBoot 获取@RestController List<@RestController>的列表?

谢谢

正如@Andrey B. Panfilov评论中指出的那样,您可以在任何 Bean 中注入ApplicationContext并使用方法getBeansWithAnnotation()来检索具有在上下文中注册的特定注释的 bean。

例子:

@Component          // or any other steriotype annotaion
@AllArgsConstructor // to make use of the constractor injection
public class MyBean {
    
    private ApplicationContext context;

    public Collection<Object> getRestControllers() {
    
        Collection<Object> controllers = context
            .getBeansWithAnnotation(RestController.class)
            .values();
        
        return controllers
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM