Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all annotated controllers with @Controller

Is there a way to get a list of all Controllers, which were annotated with @Controller? I would like to use them like:

@Autowired
public void addAll(List<Controller> controllers) throws Exception {
    for (Controller controller : controllers) {
        ...
    }
}

Thanks!

like image 706
Vojtěch Avatar asked Mar 09 '12 14:03

Vojtěch


People also ask

What happens when a class is annotated with the @controller annotation?

The @Controller annotation indicates that a particular class serves the role of a controller. There is no need to extend any controller base class or reference the Servlet API.

Can we replace @controller with @RestController?

In simple words, @RestController is @Controller + @ResponseBody. So if you are using latest spring version you can directly replace @Controller with @RestController without any issue.

Is @controller a Spring boot annotation?

In Spring Boot, the controller class is responsible for processing incoming REST API requests, preparing a model, and returning the view to be rendered as a response. The controller classes in Spring are annotated either by the @Controller or the @RestController annotation.

Can we replace @controller with @component?

There is no difference between @Component , @Service , @Controller , @Repository . @Component is the Generic annotation to represent the component of our MVC.


1 Answers

getBeansWithAnnotation()

If you have annotated them with controller ... :

@Autowired
private ListableBeanFactory listableBeanFactory;

then

Map<String, Object> controllers;
controllers = listableBeanFactory.getBeansWithAnnotation(Controller.class);
like image 173
NimChimpsky Avatar answered Oct 25 '22 14:10

NimChimpsky