Tuesday, 2 August 2011

Using the JSR 303 @GroupSequence Annotation

Yesterday’s blog covered JSR 303 groups, and today’s blog builds on that idea and demonstrates how to use the @GroupSequence annotation using the beans and custom constraints mentioned previously.

If you need to find all my blogs on JSR 303, then I suggest that you click on the ‘JSR 303’ label in the cloud below. They all follow the same Address bean validation theme.

The @GroupSequence is a simple annotation that allows you to clump together a number of groups so that they can be tested at the same time. More than that, you get to control the order in which your groups are tested.

@GroupSequence({ Default.class, AddressGroup.class })
public interface CheckAllAddressConstraints {

}

In the code above, I'm telling the the validator to check the default group, before moving on to check the AddressGroup.

Using the @GroupSequence annotation is simply a matter of adding a reference to your group sequence interface to your validate call as an additional parameter:

  @Test
 
public void countryCodeIsValid() {

   
address.setCountry("US");

    Set<ConstraintViolation<Address>> constraintViolations = validator.validate
(address,
        CheckAllAddressConstraints.
class);
    assertEquals
(0, constraintViolations.size());
 
}

No comments: