关于 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. Panfilov 在 comment 中指出的那样,您可以在任何 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/