获取SpringMVC中所有的RequestMapping映射URL地址
2018-03-24 14:12:40
869次阅读
0个评论

使用@Configuration注解配置Bean,获取RequestMappingHandlerMapping


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
public class RequestMappingHandlerConfig{
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping();
        return mapping;
    }
}

获取示例:


import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import com.zokapper.configuration.RequestMappingHandlerConfig;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {  "classpath:applicationContext-[MVC].xml","classpath:applicationContext.xml"})
public class RequestMappingHandlerConfigTest {

    @Autowired
    RequestMappingHandlerConfig requestMappingHandlerConfig;

    //Spring MVC 提取注解中URL映射
    @Test
    public void detectHandlerMethods(){
        final RequestMappingHandlerMapping requestMappingHandlerMapping = requestMappingHandlerConfig.requestMappingHandlerMapping ();
        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();

        Set<RequestMappingInfo> mappings = map.keySet();
        Map<String, String> reversedMap = new HashMap<String, String>();
        for(RequestMappingInfo info : mappings) {
            HandlerMethod method = map.get(info);
            System.out.println (method.toString()+"===>"+info.getPatternsCondition().toString());
        }
    }
}



收藏00

登录 后评论。没有帐号? 注册 一个。