简体   繁体   中英

Custom Hibernate Validator Spring Boot

I wish to use the Java 8 ReflectionParameterNameProvider Hibernate Validator to return proper parameter names instead of .argN eg getPerson.arg0

I am compiling the application with the -parameter flag and have added the following Bean to my context:

@Bean
public javax.validation.Validator validator() {
    ValidatorFactory validatorFactory = Validation.byDefaultProvider()
        .configure()
        .parameterNameProvider(new ReflectionParameterNameProvider())
        .buildValidatorFactory();

    return validatorFactory.getValidator();
}

But am still getting the old getPerson.arg0

Any ideas, Thanks?

If you are relying on Hibernate Validator's integration with Hibernate to perform the validation, I found that it was necessary to put all my configuration inside validation.xml and let Hibernate Validator bootstrap from that configuration instead.

The configuration you've specified will work for spring-specific things, but won't work for the Hibernate/Hibernate Validator integration unfortunately.

Figured it out, just had to set this in the methodValidationPostProcessor bean.

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;


@Bean
public Validator validator() {
    final ValidatorFactory validatorFactory = Validation.byDefaultProvider()
            .configure()
            .parameterNameProvider(new ReflectionParameterNameProvider())
            .buildValidatorFactory();
    return validatorFactory.getValidator();
}

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
    final MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
    methodValidationPostProcessor.setValidator(validator());
    return methodValidationPostProcessor;
}

Another solution, that also keeps all Spring defaults untouched, is to override method postProcessConfiguration() :

@Bean
static LocalValidatorFactoryBean defaultValidator() {
    LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean() {

        @Override
        protected void postProcessConfiguration(
            javax.validation.Configuration<?> configuration) {
            configuration.parameterNameProvider(new ReflectionParameterNameProvider());
        }
    };
    MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory();
    factoryBean.setMessageInterpolator(interpolatorFactory.getObject());
    return factoryBean;
}

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