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

Ale*_*min 15 java reflection spring spring-mvc

如何反射获取所有控制器的列表(最好,如果不仅注释,但也在xml中指定),匹配Spring MVC应用程序中的一些特定URL?

如果只注释,

@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
}
Run Code Online (Sandbox Code Playgroud)

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

Ral*_*lph 28

从Spring 3.1开始,就有了类RequestMappingHandlerMapping,它提供了有关RequestMappingInfo@Controller类的mapping()的信息.

@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
            }
        }
    }       
}
Run Code Online (Sandbox Code Playgroud)

重要的是,在定义控制器的spring上下文中定义此bean.


Mar*_*sch 5

您可以通过调用获得映射控制器HandlerMapping.getHandler(HTTPServletRequest).getHandler().IoC可以获取HandlerMapping实例.如果您没有HTTPServletRequest,则可以使用MockHttpServletRequest构建Request.

@Autowired
private HandlerMapping mapping;

public Object getController(String uri) {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
    // configure your request to some mapping
    HandlerExecutionChain chain = mapping.getHandler(request);
    return chain.getHandler();
}
Run Code Online (Sandbox Code Playgroud)

对不起,我现在读到你想要一个URL的所有控制器.这将使您只有一个完全匹配的控制器.这显然不是你想要的.