Spring-MVC:按名称查找映射详细信息

Spring-MVC: find mapping details by its name

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

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

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

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

但是真的很难看。有没有更简单的解决方案?

您可以使用 RequestMappingHandlerMapping 获取所有映射并根据名称过滤它们。以下是创建 api 和 returns 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,直到你可以自动装配它。