反射性地获取匹配特定URL的Spring MVC控制器列表 [英] Reflectively getting list of Spring MVC controllers matching specific url
问题描述
如何反映获取所有控制器的列表(最好,如果不仅注释,但也在xml中指定),匹配Spring MVC应用程序中的一些特定URL?
如果只注释,
@Autowired
<可以使用/ pre>
private ListableBeanFactory listableBeanFactory;
...
whatever(){
Map< String,Object> beans = listableBeanFactory.getBeansWithAnnotation(RequestMapping.class);
//迭代bean并比较RequestMapping.value()注释参数
//以生成匹配控制器列表
}
但是在更一般的情况下,当在spring.xml配置中指定控制器时该怎么办?以及如何处理请求路径参数?
解决方案从Spring 3.1开始,有一个类
RequestMappingHandlerMapping$c $ c>
,它提供有关映射的信息(RequestMappingInfo
。@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方法= item.getValue();
for(String urlPattern:mapping.getPatternsCondition()。getPatterns()){
System.out.println(
method.getBeanType()。getName()+# + method.getMethod()。getName()+
< - + urlPattern);
if(urlPattern.equals(some some url)){
//添加到匹配的METHODS
}
}
}
}
重要的是这个bean是在spring的上下文中定义的控制器已定义。
How to reflectively get list of all controllers (best if not only annotated, but also specified in xml), matching some specfic url in your Spring MVC application?
In case of annotated-only,
@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 }
could be used, but what to do in more general case, when controllers may be specified in spring.xml config? And what to do with request-path parameters?
解决方案Since Spring 3.1, there is the class
RequestMappingHandlerMapping
, it delivers information about the mapping (RequestMappingInfo
) of @Controller classes.@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 } } } }
It is important that this bean is defined in the spring context where the controllers are defined.
这篇关于反射性地获取匹配特定URL的Spring MVC控制器列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!