为什么我的@RestController 中接收到的实体将值设置为 null 而不是默认值

Why does the received entity in my @RestController is setting value to null not to default

我正在使用:

当我在我的控制器中收到我的实体时

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Long create(@RequestBody Blog blog) {
  blogService.insert(blog);
  return blog.getId();
}

我只设置了博客名称,但是Blog.java包含默认值:

private Boolean isDisabled = false;
private Boolean canCreateTags = true;
private Boolean canCreateCategories = true;
private Boolean hasRss = false;

这是我的请求正文:

{"organization":{"id":"1"},"description":"test"}

所有未发送的值似乎都是 null

但是当我使用 BlogDTO 而不是 Blog 时:

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Long create(@RequestBody BlogDTO blog) {
  blogService.insert(blog);
  return blog.getId();
}

所有值均设置为默认值。

如果你想拥有默认值,你需要在发送到 post 调用主体时明确设置

用默认值覆盖 Blog.java 的 toString 方法应该可以解决下面的问题

public class Blog {

private Boolean isDisabled = false;
private Boolean canCreateTags = true;
private Boolean canCreateCategories = true;
private Boolean hasRss = false;

    @Override
        public String toString() {
            return "Blog{" +
                    "isDisabled='" + isDisabled + '\'' +
                    ", canCreateTags='" + canCreateTags + '\'' +
                    ", canCreateCategories=" + canCreateCategories +
                    '}';
        }
    }

请参考此问答