【发布时间】:2019-04-08 04:27:25
【问题描述】:
我今天开始使用 Flux,因为它非常强大。现在我已经设置了一个完整的简单 Spring boot 2 项目来处理它,但返回的对象是空的。
我开始了一个非常简单的带有一些依赖项的 Spring Boot 项目:
- 响应式 Web(嵌入式 Netty + Spring WebFlux)
- 反应式 MongoDB(Spring Data MongoDB)
- Thymeleaf 模板引擎
- Lombok(简化 POJO 的编写)
并添加了一些代码:
控制者:
@RestController
public class ChapterController {
@Autowired
private ChapterRepository repository;
@GetMapping("/chapters")
public Flux<Chapter> listing() {
return repository.findAll();
}
}
存储库:
public interface ChapterRepository extends ReactiveCrudRepository<Chapter, String> {}
配置:(在嵌入的 Mongodb 中加载一些数据) @配置 公共类 LoadDatabase {
@Bean
CommandLineRunner init(ChapterRepository repository){
return args -> {
Flux.just(
new Chapter("The life of Batman"),
new Chapter("Batmans most glorious' code"),
new Chapter("The hero we needed but didn't deserve, Batman."))
.flatMap(repository::save)
.subscribe(System.out::println);
};
}
}
数据类:
@Data
@Document
public class Chapter {
@Id
private String id;
private String name;
public Chapter(String name) {
this.name = name;
}
}
好的,现在当我启动应用程序并访问端点时:http://localhost:8080/chapters 它返回:
[
{},
{},
{}
]
它显示的对象数量与我在 LoadDatabase 类中创建的数量相同。当我更改创建的对象数量时,它会在端点上显示该数量。
我不知道我做错了什么,我尝试调试返回的通量对象。但我什么也做不了。
我希望有人能发现我的错误!
【问题讨论】:
-
在我看来,您的
Chapter对象的 id 和 name 属性没有 getter。你是如何运行代码的?是不是某个知道 Lombok 并且会运行它的注释处理器的地方? Lombok 可能会减少您必须编写的代码量,但它对注释处理器的依赖会增加相当多的复杂性。
标签: java spring spring-boot spring-webflux