javaspringspring-bootreflectionspring-webflux

Using spring WebFlux, how can I get all the RequestHandlerMappings?


In the servlet world, I can do something like:

public class MyListener implements ApplicationListener<ApplicationReadyEvent> {

  @Override
  public void onApplicationEvent(ApplicationReadyEvent event) {
    ApplicationContext context = event.getApplicationContext();
    Map<RequestMappingInfo, HandlerMethod> endpoints = context.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();

    endpoints.forEach((info, method) -> {
      log.info("Info: {}/n method: {}", info, method);
    });
  }
}

But, the same does not work in a WebFlux server due to the RequestMappingHandlerMapping Bean not being registered.

What's the right approach here? Is this even possible?

I could just hold the event for longer, and exhaustively try and find the classes that have a @RestController on it.. but in this context I don't know the package name of the potential Controller classes.


Solution

  • Spring boot reuses a lot of classes. Specifically, there are two RequestMappingHandlerMapping.

    For servlet usage, you want to import:

    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
    

    But for reactive usage, it's:

    org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping
    

    Be careful when making a library that supports both Reactive and Servlet usage - it's easy to import the incorrect class