【问题标题】:Flux returns empty objectsFlux 返回空对象
【发布时间】:2019-04-08 04:27:25
【问题描述】:

我今天开始使用 Flux,因为它非常强大。现在我已经设置了一个完整的简单 Spring boot 2 项目来处理它,但返回的对象是空的。

我开始了一个非常简单的带有一些依赖项的 Spring Boot 项目:

  • 响应式 Web(嵌入式 Netty + Spring WebFlux)
  • 反应式 MongoDB(Spring Data MongoDB)
  • Thymeleaf 模板引擎
  • Lo​​mbok(简化 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


【解决方案1】:

您得到的是空对象,因为数据未保存并且出现问题。

您正在使用@Data lombok 注释,这就像在类上具有隐式@Getter、@Setter、@ToString、@EqualsAndHashCode 和@RequiredArgsConstructor 注释(除非如果存在任何显式编写的构造函数,则不会生成构造函数)。但有时如果未在 IDE 中正确配置,它会不起作用,因此请尝试使用属性的手动 getter 和 setter 一次。

如果手动 getter/setter 工作,请尝试以下解决 lombok 的问题。

确保您的 IDE 知道 lombok。

IntelliJ:Lombok added but getters and setters not recognized in Intellij IDEA

日食:Lombok is not generating getter and setter

如果问题仍然存在,请关注此类似主题的 cmets 之一 here

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 2014-09-29
    • 2015-02-11
    • 2020-12-21
    • 2012-02-22
    • 2019-07-17
    • 2018-08-03
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多