WebFlux 包冲突导致 handler 404

build.gradle

dependencies {
    implementation org.springframework.boot:spring-boot-starter-web
    implementation org.springframework.boot:spring-boot-starter-webflux
    testImplementation org.springframework.boot:spring-boot-starter-test
}

同时引入spring-boot-starter-web和spring-boot-starter-webflux 会导致Handler 404

handler

import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

@Component
public class TestHandler {
          
   

    public Mono<ServerResponse> get(ServerRequest serverRequest) {
          
   
        return ServerResponse.ok().body(Mono.just("name"), String.class);
    }


}

config 配置路由

import com.example.webfluxdemo.controller.TestHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

@Configuration
public class HandleConfig {
          
   

    @Autowired
    private TestHandler testHandler;

    @Bean
    public RouterFunction<ServerResponse> userRouter() {
          
   
        return RouterFunctions.route().GET("/test", testHandler::get).build();
    }
}

启动项目

请求接口

经验分享 程序员 微信小程序 职场和发展