【问题标题】:How to map @RequestBody payload to builder class如何将@RequestBody 有效负载映射到构建器类
【发布时间】:2021-03-03 13:44:09
【问题描述】:

我有一个将 RequestMessage 作为 POST 正文的端点。

我想将我的有效负载映射到我的 java 类,该类使用带有构建器模式的 Lombok,并向其中添加另一个变量 (myAccountId),该变量存在于我的 ChildDto 扩展的 ParentDto 中。

下面是我在方法 sendMessage 中的实现,但我没有看到请求消息中添加了 myAccountId

@PostMapping("/sendRequest")
public ResponseEntity<String> sendMessage(@RequestBody RequestMessage payload) {
    final RequestMessage reqDto = payload;
    reqDto.toBuilder()
        .myAccountId(accId)
        .build();
    publishMesaage(reqDto);

    return new ResponseEntity<>(HttpStatus.OK);
}

ChildDTO

 @Getter
 @ToString
 @SuperBuilder(toBuilder = true)      
 @EqualsAndHashCode(callSuper = false)
 @AllArgsConstructor(access = AccessLevel.PRIVATE)
 public class RequestMessage extends MyDTO {
 private final String name;

 }

ParentDTO

 @Data
 @SuperBuilder(toBuilder = true)
 public abstract class MyDTO implements Serializable {

 @JsonIgnore private final ObjectMapper objectMapper = new ObjectMapper();
 protected String myAccountId;

 protected MyDTO() {}


public static int hashCode(Object... objects) {
    return Arrays.deepHashCode(objects);
}

public static boolean equal(Object o1, Object o2) {
    // implementation of equals method
    return false;
}

【问题讨论】:

  • build()调用的返回值在哪里使用?
  • 您在请求正文中究竟发送了什么?
  • 我不清楚你的问题是什么。预期的行为或结果是什么,实际结果是什么?是否存在不存在的构建器方法,或者是否存在未在某处定义的 myAccountId 字段的值?
  • @knittl 我将 reqDto 传递给另一个方法 publishMesaage(reqDto);
  • @catch23 我正在使用邮递员发送 RequestMessage json。但是该 json 正文没有字段 myAccountId 。所以在将 reqDTO 传递给 publishMessage 方法之前,我需要修改我的 reqDto 以拥有 myAccountId 字段,这基本上是在我的子 DTO 扩展的父 DTO 中定义。

标签: java spring-boot java-8 lombok dto


【解决方案1】:

您永远不会使用build() 方法返回的新建对象。您需要将其返回值分配给一个引用,以便您可以使用它。在构建器上调用方法不会神奇地更新原始对象。

@PostMapping("/sendRequest")
public ResponseEntity<String> sendMessage(@RequestBody RequestMessage payload) {
    // 1. get a builder from your payload,
    // 2. modify the builder,
    // 3. store the new instance returned by `build` in variable
    final RequestMessage reqDto = payload.toBuilder()
        .myAccountId(accId)
        .build();
    // 4. pass new instance to your other method
    publishMesaage(reqDto);

    return new ResponseEntity<>(HttpStatus.OK);
}

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2012-08-06
    • 2017-03-16
    相关资源
    最近更新 更多