如何获得弹簧控制器的监听器列表?

时间:2015-02-03 12:50:07

标签: java spring

我想检索Spring控制器中所有处理程序方法的列表。我可以逐个检查所有课程,但这样需要太多时间。

2 个答案:

答案 0 :(得分:1)

您可以利用反射的力量来获取某个包中所有@RequestMapping带注释方法的列表。使用Google's reflections library这可能如下所示:

 Reflections reflections = new Reflections("my.project.prefix");

 Set<Method> handlerMethods = reflections.getMethodsAnnotatedWith(org.springframework.web.bind.annotation.RequestMapping.class)

答案 1 :(得分:1)

从版本3.1.SOMETHING开始,Spring提供RequestMappingHandlerMapping bean。该类有一个返回Map的方法,其中包含您想要的信息:getHandlerMethods()。此映射包含有关其键中@RequestMapping注释的信息,以及控制器中与其值中的映射匹配的方法。

要使用它,只需在Spring MVC应用程序的任何bean中自动装配RequestMappingHandlerMapping实例:

@Configuration
public class MyConfig {

    @Autowire
    RequestMappingHandlerMapping mappings;

    @PostConstruct // It could also be a @Bean getter, actually any method you want
    void init() {
        for (Entry<RequestMappingInfo, HandlerMethod> entry : this.mappings.getHandlerMethods().entrySet()) {
            // do something useful with the actual mapping
        }
    }
}

不是特定于您的问题,但RequestMappingHandlerMapping还提供有关拦截器,内容协商程序管理器,网址映射配置等的有用信息。

相关问题