Reputation: 587
I am using hibernate validator in my spring mvc app. With the following simple steps I am able to get the validation happen.
pom.xml
changes to add hibernate validator.@Valid
.MethodArgumentNotValidException
I don't want to add the constraints to the beans, instead want to add them to the beans dynamically. This dynamic addition need to happen during application startup and just once.
In the hibernate validator documentation, I see the following snippet.
constraintMapping.type( Car.class ).property( "manufacturer", FIELD ).constraint( new NotNullDef() )
My question is, how do I get a handle to this ConstraintMapping
instance ? I see that Spring instantiates the hibernate validator through the LocalValidatorFactoryBean
.
thanks for your help.
Upvotes: 2
Views: 3807
Reputation: 19109
You get it from the HibernateValidatorConfiguration - http://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html_single/#section-programmatic-api
HibernateValidatorConfiguration configuration = Validation
.byProvider( HibernateValidator.class )
.configure();
ConstraintMapping constraintMapping = configuration.createConstraintMapping();
constraintMapping
.type( Car.class )
.property( "manufacturer", FIELD )
.constraint( new NotNullDef() )
.property( "licensePlate", FIELD )
.ignoreAnnotations()
.constraint( new NotNullDef() )
.constraint( new SizeDef().min( 2 ).max( 14 ) )
.type( RentalCar.class )
.property( "rentalStation", METHOD )
.constraint( new NotNullDef() );
Validator validator = configuration.addMapping( constraintMapping )
.buildValidatorFactory()
.getValidator();
This mean, however, that you probably cannot use LocalValidatorFactoryBean, but you probably can just write your own.
Upvotes: 3