Small question regarding SpringBoot application, and how to get the list of classes annotated with @RestController please.
I have a simple SpringBoot application, where I have couple of my own @RestController, such as:
@RestController
public class PersonController {
@RestController
public class OrderController {
@RestController
public class PriceController {
But I am also having in my dependencies, in third party libraries I cannot control, some @RestController as well.
In my application, I would like to get the list of all the @RestController, i.e. all the classes annotated with the annotation @RestController. Something like List<@RestController>, please note the at sign @, it is not List<RestController>
What I have tried so far is to extend all my @RestController with a common interface, and get the List<MyAtRestController>, but this solution will only limit to the @RestController I have control over. Many are in the third party dependencies.
Question, how to get the List of @RestController List<@RestController> from SpringBoot please?
Thank you
CodePudding user response:
As @Andrey B. Panfilov has pointed out in the comment, you can inject ApplicationContext in any of your Beans and make use of the method getBeansWithAnnotation() to retrieve beans with a particular annotation registered in the context.
Example:
@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
}
}
