java - SpringBoot 获取应用程序的 @RestController 列表,即 List<@RestController>

标签 java spring-boot

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

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

@RestController
public class PersonController {

@RestController
public class OrderController {

@RestController
public class PriceController {

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

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

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

问题,如何获取@RestController的列表? List<@RestController>来自 SpringBoot 吗?

谢谢

最佳答案

正如 @Andrey B. Panfilovcomment 中指出的那样,您可以在任何 Bean 中注入(inject) 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
    }
}

关于java - SpringBoot 获取应用程序的 @RestController 列表,即 List<@RestController>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74841648/

相关文章:

java - Spring Boot 测试 - 没有合格的 Bean 异常

Java MethodDeclaration ClassOrInterfaceDeclaration 查找类名

java - 如何在 Spring Boot 中从 REQUEST 范围获取对象

java - 在不增加文件大小的情况下将 JPEG 图像转换为 TIFF

Java - 为什么 ClassName.this.variable 在变量为静态时起作用?

java - 如果 @Primary bean 存在,为什么我可以创建另一个 bean?

java - Spring 2.1.0.M4rabbitmq声明队列并在运行时将它们绑定(bind)到监听器

java - Spring security - authorizerequest()、anyRequest() 和authenticated() 有什么作用?

java - 邮件阅读问题?

java - 无法从 Java 中的字符串解析日期 (java.text.ParseException)