I'm using Constraint Validators (JSR-303) on my beans in a Spring MVC Controller. Given the following java bean:
public class EntityDTO {
protected Long id;
protected Integer version;
protected String someOtherField;
// getters and setters
}
I have 2 different types of constraint validation I would like to perform. Either both id
and version
are null, or both are non-null.
I can create 2 different constraint validators and assign to 2 different annotations: DTOEntityFieldsEmpty
& DTOEntityFieldsNotEmpty
. But then I have to specify the validator annotation at the bean level.
@DTOEntityFieldsEmpty
public class EntityDTO {
....
}
However, I'm looking to specify the validator that I want to use in the actual controller method level. Under normal circumstances, my method would be:
public void updateData( @RequestBody @Valid EntityDTO dto){
...
}
where the @Valid
annotation will apply the Validator that is defined in the EntityDTO object. But I'm looking to see if there is a way I can either pass a parameter at the @Valid request, or specify the validator to use.
// @Valid annotation not supported this way
public void updateData( @RequestBody @Valid(validator=DTOEntityFieldsEmpty.class) EntityDTO dto){
...
}
Is there anything I can do to get around this? I realize that I can use Spring's @InitBinder
, but that will bind a validator to the entire Controller, and not just one specific method.
I've checked both JSR-303 1.0 and 1.1, and don't see anything that jumps out at me to handle this circumstance. Similarly, I can't find anything in the Spring 3 or 4 docs either. I wonder if there might be a way using Group validation, but not entirely sure. I would need to be able to know which validator was successful or failed in the controller, and that seems a little hacky to me.
You can use Validation Groupes. Therefore you need to assign the constraints at the fields to groups and then you need to tell spring which group to validate (this can be one or more groupes), therefore Spring 3.1 introduced the @Validated
annotation.
public interface GroupA { } //empty marker interface
public interface GroupB { }
@DTOEntityFieldsEmpty(groups=GroupA.class)
@DTOEntityFieldsNotEmpty(groups=GroupB.class)
public class EntityDTO {
....
}
public void updateData(
@RequestBody @Validated({ GroupA.class }) EntityDTO dto){
...
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments