How to find all controllers in Spring MVC?

后端 未结 2 695
-上瘾入骨i
-上瘾入骨i 2020-11-28 07:01

To provide some runtime generated API documentation I want to iterate over all Spring MVC controllers. All controllers are annotated with the Spring @Controller annotation.

相关标签:
2条回答
  • 2020-11-28 07:43

    I have also came across such requirement before some months and I have achieved it using the following code snippet.

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
            scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
            for (BeanDefinition beanDefinition : scanner.findCandidateComponents("com.xxx.yyy.controllers")){
                System.out.println(beanDefinition.getBeanClassName());
            }
    

    You can also do something like this with your controllers.

    Updated the code snippet. Removed the not necessary code and just displaying the class name of the controllers for better understanding. Hope this helps you. Cheers.

    0 讨论(0)
  • 2020-11-28 07:50

    I like the approach suggested by @Japs, but would also like to recommend an alternate approach. This is based on your observation that the classpath has already been scanned by Spring, and the controllers and the request mapped methods configured, this mapping is maintained in a handlerMapping component. If you are using Spring 3.1 this handlerMapping component is an instance of RequestMappingHandlerMapping, which you can query to find the handlerMappedMethods and the associated controllers, along these lines(if you are on an older version of Spring, you should be able to use a similar approach):

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
    
    @Controller
    public class EndpointDocController {
     private final RequestMappingHandlerMapping handlerMapping;
     
     @Autowired
     public EndpointDocController(RequestMappingHandlerMapping handlerMapping) {
      this.handlerMapping = handlerMapping;
     }
      
     @RequestMapping(value="/endpointdoc", method=RequestMethod.GET)
     public void show(Model model) {
      model.addAttribute("handlerMethods", this.handlerMapping.getHandlerMethods());
     } 
    }
    

    I have provided more details on this at this url http://biju-allandsundry.blogspot.com/2012/03/endpoint-documentation-controller-for.html

    This is based on a presentation on Spring 3.1 by Rossen Stoyanchev of Spring Source.

    0 讨论(0)
提交回复
热议问题