[英]Spring (Boot) validation annotations for different layers on the same class
Given a web application with Spring Boot , Spring MVC and Spring Data (with MongoDB as a database) and a one class used to represent request on multiple layers (REST, service, persistence). 给定一个具有Spring Boot , Spring MVC和Spring Data的Web应用程序(以MongoDB作为数据库)和一个用于表示多层请求(REST,服务,持久性)的类。
Is it possible to declarative specify validation constraints on the fields of the class such that some of them would apply only for certain layers (or will be ignored by some) ? 是否可以在类的字段上声明性地指定验证约束,以使其中的某些约束仅适用于某些层(或被某些层忽略)?
Example: 例:
Entity (getter and setter autogenerated) 实体 (自动生成getter和setter)
public class User {
private String name;
@NotEmpty
private String role;
}
where @NotEmpty
is JSR 303 anotation 其中
@NotEmpty
是JSR 303注释
REST API layer REST API层
role
does not exist here role
不存在
@RestController
public class RegisterController {
@Autowired
private UserService service;
@PostMapping
public User register(@Valid User u) {
return service.createAppUser(u);
}
}
Service layer 服务层
role
is set by the implementation and is required by the persistence layer role
由实现设置,而持久层则需要
@Service
public class UserService {
@Autowired
private UserRepo repo;
private User createAppUser(User u) {
u.setRole("APP_USER");
return repo.save(u);
}
}
where repo
is Spring Data MongoRepository
. 其中
repo
是春天数据 MongoRepository
。
I can think of two approaches which solve this: 我可以想到两种解决方案:
Validator
or something else, doesn't matter - simply nothing declarative Validator
或其他方法都没关系-完全没有声明性 Both of which I don't like very much as they require lot of boilerplate and this is a trivial case. 我都不喜欢这两者,因为它们都需要大量样板,这是一个小例子。
you can use validation group and @Validated
annotation. 您可以使用验证组和
@Validated
批注。
like this: 像这样:
Entity 实体
@NotEmpty(groups = Create.class)
Method 方法
public User register(@Validated(Create.class) User u) {
return service.createAppUser(u);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.