java - 如何在 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);
}
}
我也无法让电子邮件验证正常工作。任何帮助,将不胜感激。
解决方案
推荐阅读
- node.js - 我无法删除对谷歌项目的操作
- logic - 如何在 LOGICAPPS 中截断字符串?
- go - 有没有办法将字段添加到将提供给工作流中所有活动的工作流上下文?
- angular - 使用 Angular 8 中的 Angular 9 库
- angular - 如何确保 Promise 不会更新 Angular 中过时的页面?
- python - 如何在 kivy 中创建一个能够更改笔触颜色和笔触宽度的圆形输入文本字段?
- sql-server - 从 SQL Server 触发到 Oracle
- java - 使用 Java split 获取 SQL 语句中的表名
- java - 如何有效地将对象 ADto 列表转换为对象 BVo 列表?两个对象具有相同的属性值
- r - 在 R 数据框中编辑日期和时间