pom文件,一山不容二虎,下面兩個依賴不能同時使用,因爲這次我們要用到webflux,所以註釋掉上面的web,否則,編譯沒錯誤,但網頁顯示不出來。
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-web</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
HelloHandle類
package com.example.demo;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Component
public class HelloHandle {
public Mono<ServerResponse> hello(ServerRequest request) {
//返回一個字符串 hello this is a spring boot webflux project!
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject("hello this is a spring boot webflux project!"));
}
}
HelloRouter類
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.*;
//@Configuration啓動容器+@Bean註冊Bean
@Configuration
public class HelloRouter {
@Bean
public RouterFunction<ServerResponse> routeHello(HelloHandle helloHandle) {
//接收HelloHandle傳來的字符串(顯示在網頁),更改路由
return RouterFunctions
.route(RequestPredicates.GET("/hello")
.and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),helloHandle::hello);
}
}
總結:要把上面的web註釋掉,不然會顯示不出來
轉至:https://blog.csdn.net/qq_43141611/article/details/102629456