Get All Endpoints List in Spring

There are multiple ways to do as always :

Approach 1: Using Listener :
public class EndpointsListener implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
            applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods().forEach(/*Write your code here */);
        }
    }
}

Approach 2: Using Event Listener annotation:
@Component
public class EndpointsListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(EndpointsListener.class);

    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        applicationContext.getBean(RequestMappingHandlerMapping.class)
            .getHandlerMethods().forEach((key, value) -> LOGGER.info("{} {}", key, value));
    }
}

Best Approach: Directly autowire RequestMappingHandlerMapping

@Autowired
private RequestMappingHandlerMapping requestHandlerMapping;

this.requestHandlerMapping.getHandlerMethods()
            .forEach((key, value) ->  /* whatever */));

Comments

Popular Posts