基本思路,获取WebApplicationContext,从中获取所有handlerMethod,遍历获取url
1. 拿到WebApplicationContext
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockRequestDispatcher;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
@Configuration
public class WebApplicationContextConfiguration implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Bean
public WebApplicationContext getBean() {
MockServletContext servletContext = new MockServletContext();
servletContext.setMajorVersion(2);
servletContext.setMinorVersion(4);
servletContext.setContextPath("");
XmlWebApplicationContext webApplicationContext = new XmlWebApplicationContext();
webApplicationContext.setConfigLocation("classpath*:spring-mvc.xml");
servletContext.registerNamedDispatcher("default", new MockRequestDispatcher("default"));
webApplicationContext.setServletContext(servletContext);
webApplicationContext.setParent(applicationContext);
webApplicationContext.refresh();
return webApplicationContext;
}
}
2. 从WebApplicationContext中获取url
@Test
public void testGetUrl() {
Set<String> result = new TreeSet<>();
RequestMappingHandlerMapping bean = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> handlerMethods = bean.getHandlerMethods();
for (RequestMappingInfo rmi : handlerMethods.keySet()) {
PatternsRequestCondition pc = rmi.getPatternsCondition();
Set<String> pSet = pc.getPatterns();
pSet.forEach(url -> {
if (result.contains(url)) {
System.out.println(url);
throw new RuntimeException("url重复");
}
});
result.addAll(pSet);
}
result.forEach(url -> {
System.out.println(url);
});
}
其他参考:
本文介绍了如何在Spring Framework中获取所有Controller的URL。主要思路是先获取WebApplicationContext,然后从中提取handlerMethods并遍历以得到各个URL。
1026

被折叠的 条评论
为什么被折叠?



