首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Spring-MVC:根据其名称查找映射细节

Spring-MVC:根据其名称查找映射细节
EN

Stack Overflow用户
提问于 2017-01-12 23:02:31
回答 1查看 823关注 0票数 0

Spring-MVC的@RequestMapping注释有参数"name“,可以用来标识每个资源。

在某些情况下,我需要动态访问这些信息:通过给定的名称检索映射详细信息(例如path)。

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

代码语言:javascript
复制
 ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
 scanner.addIncludeFilter(new AnnotationTypeFilter(RequestMapping.class));
 // ... find classes ... go through its methods ...

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-13 00:11:58

您可以使用RequestMappingHandlerMapping获取所有映射,并根据名称对其进行过滤。以下是创建rest api并返回api/映射的路径详细信息的代码片段。

代码语言:javascript
复制
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,直到你可以自动绑定它。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41616387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档