首页 > 解决方案 > 如何在 Spring Boot 中验证服务类中的有效负载

问题描述

我有一个 Person pojo,其中一些字段在 MyGroup 类中不能为空。

 public class Person {
     @NotNull(message = "address not null", groups = { MyGroup.class })
     private String address;

     @NotNull(message = "groupId not null", groups = { MyGroup.class })
     private UUID groupId;

     private String name;
     private String phoneNumber;

     @Email
     private String email;
     private Boolean active;
}

我只想在 active = true 时验证 pojo,所以我无法在控制器级别进行验证。

我无法在我的服务类中进行验证:

 public class PersonService {
      @Validated(MyGroup.class)
      public PersonObject createPerson(@Valid Person p) { ... }

      public PersonObject updatePerson(Person p) { ... }
 }

在我调用服务类的 PersonsController 中

@Autowired
private PersonService personService;

@PostMapping
public PersonObject createPerson(@RequestBody Person payload) {
   if (payload.getActive()) {
       // want to validate the Not null fields
       return personService.createPerson(payload);
   } else {
       // does not need to validate fields 
       return personService.updatePerson(payload);
   }
}

我也无法让电子邮件验证正常工作。任何帮助,将不胜感激。

标签: javaspring-bootvalidation

解决方案


推荐阅读