简体   繁体   中英

Reuse domain model in Hibernate-Validator with Spring Boot

I am learning SpringBoot with Hibernate Validator(which was contained in Spring-boot-starter-web),and I want to know how to reuse the same domain in different situation like

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;
}

and the situation is that:

I want to use this domain model to perform login and register and maybe other too, But I meet some trouble.

  1. In register situation, I need to validate all the attributes like(name, age, email, password)
  2. But in login situation, I just need to validate the name and password.

Is it possible to do this just use the same domain? And how to do it?

Thanks.

What you want to look into is validation groups . This way you can build sets of constraints for the same bean and then use different groups to validate in different situations. In your particular case you might have something like:

public class User {

@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;

}

and then by passing either Register or Login as a group to validate you would only perform checks on those constraints that have the corresponding groups.

How to pass these groups in Spring ? You should have a look at @Validated annotation . It has an attribute groups that you can use to specify which groups to use for validation. It would look something like:

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@Validated( Login.class ) User user) {
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM