我正在使用Hibernate Validator(包含在SpringBoot starter中)学习SpringBoot,我想知道如何在不同的情况下重用相同的域,例如
User.java
public class User {
@NotBlank(message = "username could not be empty ")
private String name;
@Max(120)
private int age;
@Range(min = 8, max = 20)
private String password;
@Email
private String email;
}情况是:
我想使用这个域模型来执行登录和注册,或者其他的,但是我遇到了一些麻烦。
是否有可能做到这一点,只使用相同的领域?那怎么做呢?
谢谢。
发布于 2018-11-09 08:53:30
您要研究的是验证组。通过这种方式,您可以为同一个bean构建一组约束,然后在不同的情况下使用不同的组进行验证。在您的特殊情况下,您可能有如下内容:
公共类用户{
@NotBlank(message = "username could not be empty ", groups = {Register.class})
private String name;
@Range(min = 8, max = 20, groups = {Register.class, Login.class})
private String password;
@Email(groups = {Register.class, Login.class})
private String email;}
然后,通过将Register或Login作为一个组进行验证,您将只对那些具有相应组的约束执行检查。
如何在春天通过这些团体?你应该看看@Validated 注解。它有一个属性groups,您可以使用它来指定用于验证的组。它看起来应该是:
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@Validated( Login.class ) User user) {
....
}https://stackoverflow.com/questions/53218330
复制相似问题