2

I am using hibernate validator in my spring mvc app. With the following simple steps I am able to get the validation happen.

  1. pom.xml changes to add hibernate validator.
  2. Annotated the beans with some constraints.
  3. Annotated the controller method parameter with @Valid.
  4. Handled the 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.

1 Answer 1

3

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.  

Sign up to request clarification or add additional context in comments.

3 Comments

I tried to register the validator in code, like so : appCtx.getAutowireCapableBeanFactory().configureBean(validator,"validator");. But, it gave errors. Is it the right way to register the validator programiatically ? is there other way ? thank you.
is it possible to assign this validator in the controller using the @InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(javax.validation.Validator instance); } But, binder is expecting the Spring validator ..
tbh, I don't know. I would ask on the Spring forum.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.