非Spring Boot环境下运行Spring WebFlux @Controller遇阻求助
Hey Simon, let's break down why your @Controller beans aren't being picked up by the WebHandler even though they're registered and you've added RequestMappingHandlerMapping. Here are the key gaps and fixes to try:
1. You're Missing RequestMappingHandlerAdapter
A HandlerMapping (like RequestMappingHandlerMapping) only maps requests to handler methods—but you need a HandlerAdapter to actually execute those methods. In a vanilla Spring setup, Spring Boot auto-registers this for you, but you have to add it manually:
@Bean public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { return new RequestMappingHandlerAdapter(); }
2. Ensure WebHandler Uses Your Mapping and Adapter
If you're using Spring WebFlux, the DispatcherHandler (which powers WebHandler) needs both the HandlerMapping and HandlerAdapter to process annotated controllers. You need to explicitly wire them into your WebHandler bean:
@Bean public WebHandler webHandler(List<HandlerMapping> handlerMappings, List<HandlerAdapter> handlerAdapters) { DispatcherHandler dispatcherHandler = new DispatcherHandler(handlerMappings, handlerAdapters); return WebHttpHandlerBuilder.webHandler(dispatcherHandler).build(); }
3. Double-Check Your Environment Stack
Make sure you're not mixing Spring MVC and WebFlux dependencies—this can cause conflicting components to load. If you intended to use traditional Spring MVC (not WebFlux), you need to use DispatcherServlet instead of WebHandler:
public static void main(String[] args) { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(YourWebConfig.class, YourController.class); context.refresh(); // Register DispatcherServlet DispatcherServlet dispatcherServlet = new DispatcherServlet(context); ServletRegistration.Dynamic reg = context.getServletContext().addServlet("dispatcher", dispatcherServlet); reg.setLoadOnStartup(1); reg.addMapping("/"); // Launch embedded Tomcat (example) Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); tomcat.addWebapp("", new File("src/main/webapp").getAbsolutePath()); tomcat.start(); }
Quick Debug Checks
- Look for logs like
Mapped "{/your-endpoint}" onto public ...—this confirms your@Controllermappings are being registered byRequestMappingHandlerMapping. - Check the full version of that partial log you shared (
Apr 13, 2018 7:27:30 PM org.spri...)—it might contain warnings about missing adapters or unprocessed mappings. - Verify your
@Controllerclasses are properly scanned (via@ComponentScan) or explicitly registered in your application context.
内容的提问来源于stack exchange,提问作者Simon

