反射性地获取与特定URL匹配的Spring MVC控制器列表


问题内容

如何以反射方式获取所有控制器的列表(最好是不仅是带注释的,而且还要在xml中指定),并与Spring MVC应用程序中的某些特定网址匹配?

在仅带注释的情况下,

@Autowired
private ListableBeanFactory listableBeanFactory;
...
whatever() {
    Map<String,Object> beans = listableBeanFactory.getBeansWithAnnotation(RequestMapping.class);

    // iterate beans and compare RequestMapping.value() annotation parameters
    // to produce list of matching controllers
}

可以使用,但是在一般情况下,如果可以在spring.xml配置中指定控制器,该怎么办?以及如何处理请求路径参数?


问题答案:

从Spring
3.1开始,存在类RequestMappingHandlerMapping,它提供有关RequestMappingInfo@Controller类的映射()的信息。

@Autowired
private RequestMappingHandlerMapping requestMappingHandlerMapping;

@PostConstruct
public void init() {
    Map<RequestMappingInfo, HandlerMethod> handlerMethods =
                              this.requestMappingHandlerMapping.getHandlerMethods();

    for(Entry<RequestMappingInfo, HandlerMethod> item : handlerMethods.entrySet()) {
        RequestMappingInfo mapping = item.getKey();
        HandlerMethod method = item.getValue();

        for (String urlPattern : mapping.getPatternsCondition().getPatterns()) {
            System.out.println(
                 method.getBeanType().getName() + "#" + method.getMethod().getName() +
                 " <-- " + urlPattern);

            if (urlPattern.equals("some specific url")) {
               //add to list of matching METHODS
            }
        }
    }       
}

在定义控制器的spring上下文中定义此bean非常重要。