简体   繁体   中英

how to execute validation on property annotated with @valid before a class level annotation?

Assume a class A associates class B, I need data validation between A and B, so I add a custom annotation on class A class level, also make it in a different group, so I can control the execution order, but it seems only work on A, I want the custom validation be executed after the basic validation done both on A and B, but it seems doesn't, the validation on B is executed after, how can make it before the custom validation? Here are the sample codes:

@XXXValidation(groups = Second.class)
@GroupSequence({A.class, Second.class})
public class A {
   @valid
   private B b;
}
public class B {
   @NotNull
   private String name;
}

Using @GroupSequence on the class level re-defines the group sequence for the Default group. This is local to the class and is not propagated to any association. The Default group will be validated in the associated class. See also the relevant chapter in the Bean Validation specification - http://beanvalidation.org/1.1/spec/#constraintdeclarationvalidationprocess-groupsequence-redefiningdefaultgroup .

@Valid is an orthogonal concept to the notion of group. If two groups are in sequence, the first group must pass for all associated objects before the second group is evaluated. Note however that the Default group sequence overriding is local to the class it is defined on and is not propagated to the associated objects.

If you want to make sure that the whole object graph is validated in a given group order, then you need to "request" this order as part of the top level call to Validator.validate . If you control validation yourself, this should be straight forward. If you are using Bean Validation as part of another framework, you will need to refer to its documentation on how to specify groups. JPA for example defines a set of properties which can be set (eg in persistence.xml ) in order to define which group(sequence)s should be evaluated as part JPA life cycle events.

Depending on your use case you might be able to use @ConvertGroup as well. Check the specification or online documentation for Hibernate Validator for examples.

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