下面列出了怎么用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
//获取上下文
ServletContext sc = servletContextEvent.getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
//获取Mapping(就是存放了所有的Controoler中@Path注解的Url映射)
RequestMappingHandlerMapping mapping = ac.getBean(RequestMappingHandlerMapping.class);
//遍历所有的handlerMethods(为了从mapping中取出Url,交给Zookeeper进行注册)
Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
for (RequestMappingInfo key : handlerMethods.keySet()) {
String serviceName = key.getName();
if(!StringUtils.isEmpty(serviceName)){
//不等于空,则拿到了服务名称,则立即注册
registry.register(serviceName,String.format("%s:%d",serverAddress,serverPort));
}
}
}
private void doTestCustomValidator(String xml) throws Exception {
loadBeanDefinitions(xml);
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
assertFalse(mapping.getUrlPathHelper().shouldRemoveSemicolonContent());
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
assertNotNull(adapter);
assertEquals(true, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));
// default web binding initializer behavior test
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("date", "2009-10-31");
MockHttpServletResponse response = new MockHttpServletResponse();
adapter.handle(request, response, handlerMethod);
assertTrue(appContext.getBean(TestValidator.class).validatorInvoked);
assertFalse(handler.recordedValidationError);
}
public static HomeModuleExtension create(String pathPrefix, Collection<RequestMappingHandlerMapping> mappings) {
HomeModuleExtension ext = new HomeModuleExtension();
for (RequestMappingHandlerMapping mapping : mappings) {
Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
for (RequestMappingInfo info : handlerMethods.keySet()) {
Set<String> patterns = info.getPatternsCondition().getPatterns();
for (String pattern : patterns) {
if (pattern.equals("/error") || pattern.contains("*")) {
continue;
}
if (pathPrefix == null) {
ext.addPath(pattern);
} else if (pattern.startsWith(pathPrefix)) {
ext.addPath(pattern.substring(pathPrefix.length()));
}
}
}
}
return ext;
}
@Test
public void testBeanDecoration() throws Exception {
loadBeanDefinitions("mvc-config-bean-decoration.xml");
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
mapping.setDefaultHandler(handlerMethod);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
HandlerExecutionChain chain = mapping.getHandler(request);
assertEquals(3, chain.getInterceptors().length);
assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
assertTrue(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor);
assertTrue(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor);
LocaleChangeInterceptor interceptor = (LocaleChangeInterceptor) chain.getInterceptors()[1];
assertEquals("lang", interceptor.getParamName());
ThemeChangeInterceptor interceptor2 = (ThemeChangeInterceptor) chain.getInterceptors()[2];
assertEquals("style", interceptor2.getParamName());
}
@Test
public void testContentNegotiationManager() throws Exception {
loadBeanDefinitions("mvc-config-content-negotiation-manager.xml");
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
ContentNegotiationManager manager = mapping.getContentNegotiationManager();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.xml");
NativeWebRequest webRequest = new ServletWebRequest(request);
assertEquals(Collections.singletonList(MediaType.valueOf("application/rss+xml")),
manager.resolveMediaTypes(webRequest));
ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class);
assertNotNull(compositeResolver);
assertEquals("Actual: " + compositeResolver.getViewResolvers(), 1, compositeResolver.getViewResolvers().size());
ViewResolver resolver = compositeResolver.getViewResolvers().get(0);
assertEquals(ContentNegotiatingViewResolver.class, resolver.getClass());
ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolver;
assertSame(manager, cnvr.getContentNegotiationManager());
}
@Test
public void requestMappingHandlerMapping() throws Exception {
ApplicationContext context = initContext(WebConfig.class, ScopedController.class, ScopedProxyController.class);
RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
assertEquals(0, handlerMapping.getOrder());
HandlerExecutionChain chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
assertNotNull(chain);
assertNotNull(chain.getInterceptors());
assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[0].getClass());
chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scoped"));
assertNotNull("HandlerExecutionChain for '/scoped' mapping should not be null.", chain);
chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scopedProxy"));
assertNotNull("HandlerExecutionChain for '/scopedProxy' mapping should not be null.", chain);
}
@Bean
@ConditionalOnMissingBean(WebMvcRegistrations.class)
public WebMvcRegistrations mvcRegistrations() {
return new WebMvcRegistrations() {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new PluginRequestMappingHandlerMapping();
}
@Override
public RequestMappingHandlerAdapter getRequestMappingHandlerAdapter() {
return null;
}
@Override
public ExceptionHandlerExceptionResolver getExceptionHandlerExceptionResolver() {
return null;
}
};
}
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
loadBeanDefinitions("mvc-config-custom-conversion-service.xml");
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
mapping.setDefaultHandler(handlerMethod);
// default web binding initializer behavior test
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
request.setRequestURI("/accounts/12345");
request.addParameter("date", "2009-10-31");
MockHttpServletResponse response = new MockHttpServletResponse();
HandlerExecutionChain chain = mapping.getHandler(request);
assertEquals(1, chain.getInterceptors().length);
assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
interceptor.preHandle(request, response, handler);
assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
assertNotNull(adapter);
adapter.handle(request, response, handlerMethod);
}
private void doTestCustomValidator(String xml) throws Exception {
loadBeanDefinitions(xml);
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
assertFalse(mapping.getUrlPathHelper().shouldRemoveSemicolonContent());
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
assertNotNull(adapter);
assertEquals(true, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));
// default web binding initializer behavior test
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("date", "2009-10-31");
MockHttpServletResponse response = new MockHttpServletResponse();
adapter.handle(request, response, handlerMethod);
assertTrue(appContext.getBean(TestValidator.class).validatorInvoked);
assertFalse(handler.recordedValidationError);
}
@Test(expected = TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 14);
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
mapping.setDefaultHandler(handlerMethod);
// default web binding initializer behavior test
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
request.setRequestURI("/accounts/12345");
request.addParameter("date", "2009-10-31");
MockHttpServletResponse response = new MockHttpServletResponse();
HandlerExecutionChain chain = mapping.getHandler(request);
assertEquals(1, chain.getInterceptors().length);
assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
interceptor.preHandle(request, response, handler);
assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
assertNotNull(adapter);
adapter.handle(request, response, handlerMethod);
}
@Test
public void testPathMatchingHandlerMappings() throws Exception {
loadBeanDefinitions("mvc-config-path-matching-mappings.xml");
RequestMappingHandlerMapping requestMapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(requestMapping);
assertEquals(TestPathHelper.class, requestMapping.getUrlPathHelper().getClass());
assertEquals(TestPathMatcher.class, requestMapping.getPathMatcher().getClass());
SimpleUrlHandlerMapping viewController = appContext.getBean(VIEWCONTROLLER_BEAN_NAME, SimpleUrlHandlerMapping.class);
assertNotNull(viewController);
assertEquals(TestPathHelper.class, viewController.getUrlPathHelper().getClass());
assertEquals(TestPathMatcher.class, viewController.getPathMatcher().getClass());
for (SimpleUrlHandlerMapping handlerMapping : appContext.getBeansOfType(SimpleUrlHandlerMapping.class).values()) {
assertNotNull(handlerMapping);
assertEquals(TestPathHelper.class, handlerMapping.getUrlPathHelper().getClass());
assertEquals(TestPathMatcher.class, handlerMapping.getPathMatcher().getClass());
}
}
public boolean hasApiRegistered(String api,String requestMethod){
notBlank(api,"api cant not be null");
notBlank(requestMethod,"requestMethod cant not be null");
RequestMappingHandlerMapping requestMappingHandlerMapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
for (RequestMappingInfo info : map.keySet()) {
for(String pattern :info.getPatternsCondition().getPatterns()){
if(pattern.equalsIgnoreCase(api)){ // 匹配url
if(info.getMethodsCondition().getMethods().contains(getRequestMethod(requestMethod))){ // 匹配requestMethod
return true;
}
}
}
}
return false;
}
public ApiBean registerApi(String index,String api,String requestMethod,String msg){
check(!hasMethodOccupied(index),"该序号已经被占用,请先注销api。");
check(!hasApiRegistered(api,requestMethod),"该api已经注册过了");
RequestMappingHandlerMapping requestMappingHandlerMapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
Method targetMethod = ReflectionUtils.findMethod(ApiController.class, getHandlerMethodName(index)); // 找到处理该路由的方法
PatternsRequestCondition patternsRequestCondition = new PatternsRequestCondition(api);
RequestMethodsRequestCondition requestMethodsRequestCondition = new RequestMethodsRequestCondition(getRequestMethod(requestMethod));
RequestMappingInfo mapping_info = new RequestMappingInfo(patternsRequestCondition, requestMethodsRequestCondition, null, null, null, null, null);
requestMappingHandlerMapping.registerMapping(mapping_info, "apiController", targetMethod); // 注册映射处理
// 保存注册信息到本地
ApiBean apiInfo = new ApiBean();
apiInfo.setApi(api);
apiInfo.setRequestMethod(requestMethod);
apiInfo.setMsg(msg);
Constants.requestMappings.put(index,apiInfo);
return apiInfo;
}
@Test
public void requestMappingHandlerMapping() throws Exception {
ApplicationContext context = initContext(WebConfig.class, ScopedController.class, ScopedProxyController.class);
RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
assertEquals(0, handlerMapping.getOrder());
HandlerExecutionChain chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
assertNotNull(chain);
assertNotNull(chain.getInterceptors());
assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[0].getClass());
chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scoped"));
assertNotNull("HandlerExecutionChain for '/scoped' mapping should not be null.", chain);
chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/scopedProxy"));
assertNotNull("HandlerExecutionChain for '/scopedProxy' mapping should not be null.", chain);
}
@Test
public void getTest() {
RequestMappingHandlerMapping handlerMapping = Mockito.mock(RequestMappingHandlerMapping.class);
ExposedEndpointsController controller = new ExposedEndpointsController(new Gson(), handlerMapping);
String endpoint1 = "/api/test";
String endpoint2 = "/api/other/test";
Map<RequestMappingInfo, HandlerMethod> handlerMethods = new HashMap<>();
RequestMappingInfo info = new RequestMappingInfo(new PatternsRequestCondition(endpoint1, endpoint2), new RequestMethodsRequestCondition(RequestMethod.GET, RequestMethod.POST), null, null, null, null, null);
handlerMethods.put(info, null);
Mockito.when(handlerMapping.getHandlerMethods()).thenReturn(handlerMethods);
ResponseEntity<String> responseEntity = controller.get();
Assertions.assertTrue(StringUtils.isNotBlank(responseEntity.getBody()), "Expected the response body to contain json");
}
public void defaultHandlerMappings() throws Exception {
StaticWebApplicationContext cxt = new StaticWebApplicationContext();
cxt.refresh();
List<HandlerMapping> actual = getIntrospector(cxt).getHandlerMappings();
assertEquals(2, actual.size());
assertEquals(BeanNameUrlHandlerMapping.class, actual.get(0).getClass());
assertEquals(RequestMappingHandlerMapping.class, actual.get(1).getClass());
}
/**
* We mention this in the book, but this helps to ensure that the intercept-url patterns prevent access to our
* controllers. For example, once security has been applied for administrators try commenting out the modifications
* to the super class and requesting <a
* href="http://localhost:800/calendar/events/.html">http://localhost:800/calendar/events/.html</a>. You will
* observe that security is bypassed since it did not match the pattern we provided. In later chapters, we discuss
* how to secure the service tier which helps mitigate bypassing of the URL based security too.
*/
// FIXME: FInd out what this is and why it is here.
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping result = new RequestMappingHandlerMapping();
result.setUseSuffixPatternMatch(false);
result.setUseTrailingSlashMatch(false);
return result;
}
@Test
public void contentNegotiation() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.json");
NativeWebRequest webRequest = new ServletWebRequest(request);
RequestMappingHandlerMapping mapping = this.config.requestMappingHandlerMapping(
this.config.mvcContentNegotiationManager(), this.config.mvcConversionService(),
this.config.mvcResourceUrlProvider());
ContentNegotiationManager manager = mapping.getContentNegotiationManager();
assertEquals(Collections.singletonList(APPLICATION_JSON), manager.resolveMediaTypes(webRequest));
request.setRequestURI("/foo.xml");
assertEquals(Collections.singletonList(APPLICATION_XML), manager.resolveMediaTypes(webRequest));
request.setRequestURI("/foo.rss");
assertEquals(Collections.singletonList(MediaType.valueOf("application/rss+xml")),
manager.resolveMediaTypes(webRequest));
request.setRequestURI("/foo.atom");
assertEquals(Collections.singletonList(APPLICATION_ATOM_XML), manager.resolveMediaTypes(webRequest));
request.setRequestURI("/foo");
request.setParameter("f", "json");
assertEquals(Collections.singletonList(APPLICATION_JSON), manager.resolveMediaTypes(webRequest));
request.setRequestURI("/resources/foo.gif");
SimpleUrlHandlerMapping handlerMapping = (SimpleUrlHandlerMapping) this.config.resourceHandlerMapping(
this.config.mvcUrlPathHelper(), this.config.mvcPathMatcher(),
this.config.mvcContentNegotiationManager(), this.config.mvcConversionService(),
this.config.mvcResourceUrlProvider());
handlerMapping.setApplicationContext(this.context);
HandlerExecutionChain chain = handlerMapping.getHandler(request);
assertNotNull(chain);
ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) chain.getHandler();
assertNotNull(handler);
assertSame(manager, handler.getContentNegotiationManager());
}
/**
* Return a {@link RequestMappingHandlerMapping} ordered at 0 for mapping
* requests to annotated controllers.
*/
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();
mapping.setOrder(0);
mapping.setInterceptors(getInterceptors());
mapping.setContentNegotiationManager(mvcContentNegotiationManager());
mapping.setCorsConfigurations(getCorsConfigurations());
PathMatchConfigurer configurer = getPathMatchConfigurer();
if (configurer.isUseSuffixPatternMatch() != null) {
mapping.setUseSuffixPatternMatch(configurer.isUseSuffixPatternMatch());
}
if (configurer.isUseRegisteredSuffixPatternMatch() != null) {
mapping.setUseRegisteredSuffixPatternMatch(configurer.isUseRegisteredSuffixPatternMatch());
}
if (configurer.isUseTrailingSlashMatch() != null) {
mapping.setUseTrailingSlashMatch(configurer.isUseTrailingSlashMatch());
}
UrlPathHelper pathHelper = configurer.getUrlPathHelper();
if (pathHelper != null) {
mapping.setUrlPathHelper(pathHelper);
}
PathMatcher pathMatcher = configurer.getPathMatcher();
if (pathMatcher != null) {
mapping.setPathMatcher(pathMatcher);
}
return mapping;
}
@Override
protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
LOGGER.debug("Creating requestMappingHandlerMapping");
RequestMappingHandlerMapping requestMappingHandlerMapping = new RequestMappingHandlerMapping();
requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
return requestMappingHandlerMapping;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof RequestMappingHandlerMapping) {
RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) bean;
// URL decode after request mapping, not before.
requestMappingHandlerMapping.setUrlDecode(false);
}
return bean;
}
public RequestMappingHandlerMapping getHandlerMapping(
FormattingConversionService mvcConversionService,
ResourceUrlProvider mvcResourceUrlProvider) {
RequestMappingHandlerMapping handlerMapping = handlerMappingFactory.get();
handlerMapping.setEmbeddedValueResolver(new StaticStringValueResolver(placeholderValues));
handlerMapping.setUseSuffixPatternMatch(useSuffixPatternMatch);
handlerMapping.setUseTrailingSlashMatch(useTrailingSlashPatternMatch);
handlerMapping.setOrder(0);
handlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
if (removeSemicolonContent != null) {
handlerMapping.setRemoveSemicolonContent(removeSemicolonContent);
}
return handlerMapping;
}
@RequestMapping("getAllUrl")
@ResponseBody
public Set<String> getAllUrl(HttpServletRequest request) {
Set<String> result = new HashSet<>();
WebApplicationContext wc = (WebApplicationContext) request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
RequestMappingHandlerMapping bean = wc.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> handlerMethods = bean.getHandlerMethods();
for (RequestMappingInfo rmi : handlerMethods.keySet()) {
PatternsRequestCondition pc = rmi.getPatternsCondition();
Set<String> pSet = pc.getPatterns();
result.addAll(pSet);
}
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
return result;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof RequestMappingHandlerMapping) {
RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) bean;
// URL decode after request mapping, not before.
requestMappingHandlerMapping.setUrlDecode(false);
}
return bean;
}
/**
* 预设置添加允许访问路径
*
* @param http HttpSecurity
* @throws Exception 配置异常
*/
protected void presetConfigure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry urlRegistry =
http.authorizeRequests()
// 跨域预检请求
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// 登录
.antMatchers(props.getLoginUrl()).permitAll()
.antMatchers(props.getPermitURLs().toArray(new String[0])).permitAll();
if (!CollectionUtils.isEmpty(props.getAdditionPermitUrls())) {
urlRegistry.antMatchers(props.getAdditionPermitUrls().toArray(new String[0])).permitAll();
}
// 标记匿名访问
Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
Set<String> anonUrls = new HashSet<>();
for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) {
HandlerMethod handlerMethod = infoEntry.getValue();
CrustAnon crustAnon = handlerMethod.getMethodAnnotation(CrustAnon.class);
if (null != crustAnon) {
anonUrls.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
}
}
if (!CollectionUtils.isEmpty(anonUrls)) {
urlRegistry.antMatchers(anonUrls.toArray(new String[0])).permitAll();
}
// 自定义额外允许路径
additionalConfigure(urlRegistry, http);
// 其他所有请求需要身份认证
urlRegistry.anyRequest().authenticated();
}
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
LOGGER.debug("Creating requestMappingHandlerMapping");
RequestMappingHandlerMapping requestMappingHandlerMapping = new RequestMappingHandlerMapping();
requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
requestMappingHandlerMapping.setRemoveSemicolonContent(false);
Object[] interceptors = { localeChangeInterceptor() };
requestMappingHandlerMapping.setInterceptors(interceptors);
return requestMappingHandlerMapping;
}
@Autowired
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public void configRequestMappingHandlerMapping(RequestMappingHandlerMapping requestMappingHandlerMapping) {
// 使用内置拦截器
SpringMvcPolyfill.addDynamicInterceptor(cometInterceptor(), Ordered.HIGHEST_PRECEDENCE, Collections.singletonList("/**"),
null, requestMappingHandlerMapping);
}
public PluginControllerPostProcessor(ApplicationContext applicationContext){
Objects.requireNonNull(applicationContext);
this.springBeanRegister = new SpringBeanRegister(applicationContext);
this.applicationContext = (GenericApplicationContext) applicationContext;
this.requestMappingHandlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
this.integrationConfiguration = applicationContext.getBean(IntegrationConfiguration.class);
}
/**
* 注册单一插件
* @param pluginRegistryInfo 注册的插件信息
* @param aClass controller 类
* @return ControllerBeanWrapper
* @throws Exception Exception
*/
private ControllerBeanWrapper registry(PluginRegistryInfo pluginRegistryInfo, Class<?> aClass)
throws Exception {
String pluginId = pluginRegistryInfo.getPluginWrapper().getPluginId();
String beanName = springBeanRegister.register(pluginId, aClass);
if(beanName == null || "".equals(beanName)){
throw new IllegalArgumentException("registry "+ aClass.getName() + "failure!");
}
try {
Object object = applicationContext.getBean(beanName);
if(object == null){
throw new Exception("registry "+ aClass.getName() + "failure! " +
"Not found The instance of" + aClass.getName());
}
ControllerBeanWrapper controllerBeanWrapper = new ControllerBeanWrapper();
controllerBeanWrapper.setBeanName(beanName);
setPathPrefix(pluginId, aClass);
Method getMappingForMethod = ReflectionUtils.findMethod(RequestMappingHandlerMapping.class,
"getMappingForMethod", Method.class, Class.class);
getMappingForMethod.setAccessible(true);
Method[] methods = aClass.getMethods();
Set<RequestMappingInfo> requestMappingInfos = new HashSet<>();
for (Method method : methods) {
if (isHaveRequestMapping(method)) {
RequestMappingInfo requestMappingInfo = (RequestMappingInfo)
getMappingForMethod.invoke(requestMappingHandlerMapping, method, aClass);
requestMappingHandlerMapping.registerMapping(requestMappingInfo, object, method);
requestMappingInfos.add(requestMappingInfo);
}
}
controllerBeanWrapper.setRequestMappingInfos(requestMappingInfos);
controllerBeanWrapper.setBeanClass(aClass);
return controllerBeanWrapper;
} catch (Exception e){
// 出现异常, 卸载该 controller bean
springBeanRegister.unregister(pluginId, beanName);
throw e;
}
}
@Bean
public RequestMappingHandlerMapping defaultTestHandlerMapping(GreetingController greetingController) throws NoSuchMethodException {
RequestMappingHandlerMapping result = new RequestMappingHandlerMapping();
RequestMappingInfo requestMappingInfo =
RequestMappingInfo.paths("/test").methods(RequestMethod.GET).produces(MediaType.APPLICATION_JSON_VALUE).build();
result.setApplicationContext(this.applicationContext);
result.registerMapping(requestMappingInfo, "greetingController", GreetingController.class.getDeclaredMethod("sayHello2"));
//result.handlerme
return result;
}