【问题标题】:Spring-MVC: find mapping details by its nameSpring-MVC:按名称查找映射详细信息
【发布时间】:2017-01-12 15:02:31
【问题描述】:

Spring-MVC 的@RequestMapping 注解有参数“name”,可用于标识每个资源。

在某些情况下,我需要即时访问此信息:按给定名称检索映射详细信息(例如 path)。

当然,我可以通过以下方式扫描类以查找此注释并检索所需的实例:

 ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
 scanner.addIncludeFilter(new AnnotationTypeFilter(RequestMapping.class));
 // ... find classes ... go through its methods ...

但它很丑陋。还有更简单的解决方案吗?

【问题讨论】:

    标签: java spring spring-mvc annotations request-mapping


    【解决方案1】:

    您可以使用RequestMappingHandlerMapping 获取所有映射并根据名称过滤它们。下面是一段代码 sn-p,它创建一个 rest api 并返回一个 api/mapping 的路径详细信息。

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
    import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
    
    @RestController
    public class EndpointController {
    
        @Autowired
        private RequestMappingHandlerMapping handlerMapping;
    
        @GetMapping("endpoints/{name}")
        public String show(@PathVariable("name") String name) {
            String output = name + "Not Found";
            Map<RequestMappingInfo, HandlerMethod> methods = this.handlerMapping.getHandlerMethods();
    
            for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : methods.entrySet()) {
                if (entry.getKey().getName() != null && entry.getKey().getName().equals(name)) {
                    output = entry.getKey().getName() + " : " + entry.getKey();
                    break;
                }
            }
            return output;
        }
    }
    

    以上只是一个例子,你可以随意使用RequestMappingHandlerMapping,直到你可以自动装配它。

    【讨论】:

      猜你喜欢
      • 2016-03-26
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-02
      • 2021-06-01
      • 2020-11-04
      • 1970-01-01
      相关资源
      最近更新 更多