spring-boot - Spring 启动 : How to make a field as mandatory in POST request while in PUT request it should be optional

标签 spring-boot annotations entity

我正在使用实体类。 考虑在 POST 请求和更新的请求正文中,字段“名称”是必需的,即在 PUT 请求中,“名称”字段应该是可选的。我们不需要再次传递“名称”字段,这是没有必要的。所以我想在 POST 请求正文中强制设置“Name”属性,在 PUT 请求正文中设置为可选属性。

最佳答案

您可以在 JSR303 注释中使用组参数。

@NotEmpty 注释适用于通过“现有”接口(interface)访问时:

public class Greeting {

  private final long id;
  @NotEmpty(groups = Existing.class)
  private final String content;

  public Greeting(long id, String content) {
      this.id = id;
      this.content = content;
  }

  public long getId() {
      return id;
  }

  public String getContent() {
      return content;
  }

  public interface Existing {
  }
}

注意 PutMapping 上的 @Validated(Existing.class) 注解

@PostMapping("/greeting")
public Greeting newGreeting( @RequestBody Greeting gobj) {
    return new Greeting(counter.incrementAndGet(),
            String.format(template, gobj.getContent()));
}

@PutMapping("/greeting")
public Greeting updateGreeting(@Validated(Existing.class) @RequestBody Greeting gobj) {
    return new Greeting(gobj.getId(),
            String.format(template, gobj.getContent()));
}

对于上面的示例,Json 正文 {"id": 1} 将适用于 POST,但对于 PUT,您将收到 HTTP 400,告诉您“内容参数不能为空”。 {"id": 1, "content":"World"} 将被两种方法接受。

关于spring-boot - Spring 启动 : How to make a field as mandatory in POST request while in PUT request it should be optional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53979988/

相关文章:

hibernate - spring + hibernate - 将实体映射到不同的数据源

java - 如何限制用户在 OTP 生成 4 小时后通过 OTP 验证手机

java - 使用 postman 测试具有 RequestParam 的休息服务

spring-boot - Spring 引导 REST API : SpringDoc + OpenAPI 3 (springdoc-openapi-ui) or Swagger2 v3 (springfox-boot-starter)

logging - Spring Boot : How to disable startup log message "Starting Application on mbp with PID 99446"

java类<?扩展实体>如何获取实体实例

java - 使用注释配置引用多个bean

java - "@annotations must be on separate line"的 Checkstyle 规则

python - 新的注释打破了对数据类的检查

domain-driven-design - "Save"方法是否属于业务域实体?