Search code examples
javaspringspring-mvcannotationsrequest-mapping

Spring-MVC: find mapping details by its name


Spring-MVC's @RequestMapping annotation has parameter "name" which can be used for identifying each resource.

For some circumstances I need access this information on fly: retrieve mapping details (e.g. path) by given name.

Sure I can scan for classes for this annotation and retrieve needed instances via:

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

But it is quite ugly. Is any more simple solution?


Solution

  • You can use RequestMappingHandlerMapping to get all your mappings and filter them based on name. Following is a code snippet which creates a rest api and returns the path details of a 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;
        }
    }
    

    The above is just an example, You can use the RequestMappingHandlerMapping anyway you want until you can autowire it.