Java 如何在Spring boot中修改Mono对象的属性而不阻塞它

Java 如何在Spring boot中修改Mono对象的属性而不阻塞它,java,spring-boot,reactive-programming,spring-webflux,Java,Spring Boot,Reactive Programming,Spring Webflux,我最近开始使用reactive,并创建了一个使用reactive流的简单应用程序 我有以下代码,我通过empID获得一名员工。只有当showExtraDetailsboolean设置为true时,我才需要向API提供有关员工的额外详细信息。如果设置为false,我必须在返回employee对象之前将额外的详细信息设置为null。现在我正在使用流上的一个块来实现这一点。有没有可能在没有阻塞的情况下执行此操作,以便我的方法可以返回Mono 下面是我已经完成的代码 public Employee ge

我最近开始使用reactive,并创建了一个使用reactive流的简单应用程序

我有以下代码,我通过empID获得一名员工。只有当
showExtraDetails
boolean设置为
true
时,我才需要向API提供有关员工的额外详细信息。如果设置为false,我必须在返回employee对象之前将额外的详细信息设置为null。现在我正在使用流上的一个块来实现这一点。有没有可能在没有阻塞的情况下执行此操作,以便我的方法可以返回Mono

下面是我已经完成的代码

public Employee getEmployee(String empID, boolean showExtraDetails) {


    Query query = new Query();

    query.addCriteria(Criteria.where("empID").is(empID));


    Employee employee = reactiveMongoTemplate.findOne(query, Employee.class, COLLECTION_NAME).block();


    if (employee != null) {

        logger.info("employee {} found", empID);
    }


    if (employee != null && !showExtraDetails) {

        employee.getDetails().setExtraDetails(null);
    }

    return employee;

}  

试一试,假设
reactiveMongoTemplate
是您的mongo存储库,应该是这样工作的

return reactiveMongoTemplate.findById(empID).map(employee -> {
            if (!showExtraDetails) {
              employee.getDetails().setExtraDetails(null);
            }
            return employee;                
        });

这里不需要flatMap,map也可以做同样的工作。reactiveMongoTemplate.findById(empID).map(employee->employee.getDetails().setExtraDetails(null))在空的情况下,不会执行map操作符,因此
map
这里是一个不错的选择。这是否意味着我不必进行单独的null检查@BrianClozelper反应流规范,不允许
Mono
Flux
提供
null
元素。因此,
Mono
要么提供一个元素,要么什么都不提供(
Mono.empty()