@RestController 如何用
时间: 2023-06-29 10:19:19 浏览: 54
在Spring WebFlux中,可以使用`@RestController`注解来标记一个类,表示这个类中的方法都是处理HTTP请求的方法,且返回值会自动转换为JSON格式。例如:
```
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class HelloController {
@GetMapping("/hello")
public Mono<String> hello() {
return Mono.just("Hello, World!");
}
}
```
在上面的例子中,我们使用`@RestController`注解标记了`HelloController`类,表示这个类中的方法都是处理HTTP请求的方法。在`hello()`方法中,我们返回了一个`Mono<String>`类型的数据,它表示一个异步计算的结果,这个结果会被转换为JSON格式返回给客户端。在本例中,我们返回了一个字符串"Hello, World!"。
在使用`@RestController`注解时,Spring会使用Jackson库将返回值自动序列化为JSON格式,然后返回给客户端。如果需要自定义序列化方式,可以使用`@JsonSerialize`和`@JsonDeserialize`注解来标记实体类中的属性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)