Spring-MVC的@RequestMapping注释有参数"name“,可以用来标识每个资源。
在某些情况下,我需要动态访问这些信息:通过给定的名称检索映射详细信息(例如path)。
当然,我可以扫描此注释的类,并通过以下方式检索所需的实例:
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(RequestMapping.class));
// ... find classes ... go through its methods ...但它相当丑陋。还有更简单的解决方案吗?
发布于 2017-01-13 00:11:58
您可以使用RequestMappingHandlerMapping获取所有映射,并根据名称对其进行过滤。以下是创建rest api并返回api/映射的路径详细信息的代码片段。
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,直到你可以自动绑定它。
https://stackoverflow.com/questions/41616387
复制相似问题