Spring反应返回scanAvailable和Prefetch而不是Object

2022-04-06 00:00:00 spring java spring-boot spring-webflux

我有一个用Spring active开发的rest API,如下所示,当它返回响应时,它确实有scanAvailable和预取,而不是对象详细信息。对于findAllEmployee,getAllWorkerAddressDetailsByWorkerId下面使用的方法,我们有单独的API,它确实返回了正确的响应。当我将它们组合在一起时,我不确定哪里出了问题。

WorkerDTO.java

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString(includeFieldNames = true)
public class WorkerDTO {
    
    ...

    private Flux<WorkerAddressDTO> workerAddress;

}

ServiceImpl.java

@Override
public Flux<WorkerDTO> method() {
  Flux<EmploymentDTO> employmentDTOFlux = findAllEmployment();
  Flux<WorkerDTO> workerDTOFlux = getWorkerDetailsWithEmploymentStatus(employmentDTOFlux);
  return workerDTOFlux.flatMap(workerDTO -> {
    workerDTO.setWorkerAddress(getAllWorkerAddressDetailsByWorkerId(workerDTO.getWorkerId()).map(workerAddressDTO -> workerAddressDTO));
     return Flux.just(workerDTO);
  });
}

当前响应:

[
    {
        "xyz": "abc",
        "workerAddress": {
            "scanAvailable": true,
            "prefetch": -1
        }
    },
    {
       "xyz": "qwe",
        "workerAddress": {
            "scanAvailable": true,
            "prefetch": -1
        }
    } 
]

预期响应:

[
    {
        "xyz": "abc",
        "workerAddress": {
            "key1": "value1",
            "key2": "value2"
        }
    },
    {
       "xyz": "qwe",
        "workerAddress": {
            "key1": "value1",
            "key2": "value2"
        }
    } 
]

解决方案

您需要做一些更改。首先,将Flux放在WorkerDTO中,并替换为List,如下所示:

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString(includeFieldNames = true)
public class WorkerDTO {
    
    ...

    private List<WorkerAddressDTO> workerAddress;
}

然后,您需要按如下方式更改ServiceImpl代码:

@Override
public Flux<WorkerDTO> method() {
    Flux<EmploymentDTO> employmentDTOFlux = findAllEmployment();
    Flux<WorkerDTO> workerDTOFlux = getWorkerDetailsWithEmploymentStatus(employmentDTOFlux);
    return workerDTOFlux.flatMap(workerDTO -> {
         return getAllWorkerAddressDetailsByWorkerId(workerDTO.getWorkerId()).collectList()
            .map(workerAddresses -> workerDTO.setWorkerAddress(workerAddresses));
    });
}

相关文章