我想检索Spring控制器中所有处理程序方法的列表。我可以逐个检查所有课程,但这样需要太多时间。
答案 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
还提供有关拦截器,内容协商程序管理器,网址映射配置等的有用信息。