Search code examples
springrestspring-web

Spring RestController endpoints autodiscovery


Is there a way to get a list of all the endpoints declared in a @RestController annotated class? With some patience that could be achieved via reflections but is there any Spring built-in way for that? Idea is to show this list on a service landing page.


Solution

  • A registry of all the handler mappings is kept in the requestMappingHandlerMapping bean. You can access it from your Spring Boot Application's main method like this.

    public static void main(String[] args) {
        ConfigurableApplicationContext context = 
                SpringApplication.run(MySpringApplication.class, args);
    
        AbstractHandlerMethodMapping requestMappingHandlerMapping = 
                context.getBean("requestMappingHandlerMapping", AbstractHandlerMethodMapping.class);
        Map handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
        System.out.println("handlerMethods: " + handlerMethods);
    }
    

    Or just autowire the bean into whichever of your Spring beans you need it in.