简体   繁体   中英

What is the idea of using groups in Bean Validation

What is the idea of using groups in short? For example, the class definition has no groups now. What's going to change if we enable groups below?

//  @Size(min = 4, max = 30, groups = LengthGroup.class)
    @Size(min = 4, max = 30)
    private String name;

//  @Size(min = 12, max = 120, groups = LengthGroup.class)
    @Size(min = 12, max = 120)
    private String address;

//  @Size(min = 5, max = 30, groups = LengthGroup.class)
    @Size(min = 5, max = 30)
    @EmailAddress//(groups = EmailGroup.class)
    private String email;

ps there are also two corresponding interfaces for those groups

In addition what kocko said, they are also meant to categorize validation rules. Quoting from the JSR-303 final spec :

Groups allow you to restrict the set of constraints applied during validation.

If you re-add the groups mentioned above and call the validatior like this: validator.validate(user, LengthGroup.class); , the lengths of your fields only will be validated. This means that the @EmailAddress constraint is not taken into consideration.

If you call the validator like this: validator.validate(user, LengthGroup.class, EmailGroup.class); , all your constraints will be validated against.

A use-case more intended for this feature would be validation a version of the user with contact data, and one without. Consider the folling example:

@Size(min = 4, max = 30)
private String name;

@Size(min = 12, max = 120, groups=WithContactInfo.class)
private String address;

@Size(min = 5, max = 30, groups= WithContactInfo.class)
@EmailAddress(groups = WithContactInfo.class)
private String email;

Now you could validate a user that does not need to have contact info with validator.validate(user) , and a user that needs to have contact info too with validator.validate(user, WithContactInfo.class) .

It is often useful to declare the same constraint more than once to the same target, with different properties. That's what the group is about. Consider this example:

public class Address {
    @ZipCode.List( {
            @ZipCode(countryCode="fr", groups=Default.class
                     message = "zip code is not valid"),
            @ZipCode(countryCode="fr", groups=SuperUser.class
                     message = "zip code invalid. Requires overriding before saving.")
            } )
    private String zipcode;
}

In this example, both constraints apply to the zipcode field but with different groups and with different error messages.

Example taken from here .

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