![](/img/trans.png)
[英]Spring boot and Bean validation in different methods and the same class
[英]Spring (Boot) validation annotations for different layers on the same class
给定一个具有Spring Boot , Spring MVC和Spring Data的Web应用程序(以MongoDB作为数据库)和一个用于表示多层请求(REST,服务,持久性)的类。
是否可以在类的字段上声明性地指定验证约束,以使其中的某些约束仅适用于某些层(或被某些层忽略)?
例:
实体 (自动生成getter和setter)
public class User {
private String name;
@NotEmpty
private String role;
}
其中@NotEmpty
是JSR 303注释
REST API层
role
不存在
@RestController
public class RegisterController {
@Autowired
private UserService service;
@PostMapping
public User register(@Valid User u) {
return service.createAppUser(u);
}
}
服务层
role
由实现设置,而持久层则需要
@Service
public class UserService {
@Autowired
private UserRepo repo;
private User createAppUser(User u) {
u.setRole("APP_USER");
return repo.save(u);
}
}
其中repo
是春天数据 MongoRepository
。
我可以想到两种解决方案:
Validator
或其他方法都没关系-完全没有声明性 我都不喜欢这两者,因为它们都需要大量样板,这是一个小例子。
您可以使用验证组和@Validated
批注。
像这样:
实体
@NotEmpty(groups = Create.class)
方法
public User register(@Validated(Create.class) User u) {
return service.createAppUser(u);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.