自定义Hibernate Validator Spring Boot

时间:2016-07-31 15:58:54

标签: java spring hibernate spring-boot

我希望使用Java 8 ReflectionParameterNameProvider Hibernate Validator返回正确的参数名称而不是 .argN ,例如getPerson.arg0

我正在使用-parameter标志编译应用程序并将以下Bean添加到我的上下文中:

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

    return validatorFactory.getValidator();
}

但我仍然得到旧的getPerson.arg0

任何想法,谢谢?

2 个答案:

答案 0 :(得分:1)

如果您依靠Hibernate Validator与Hibernate的集成来执行验证,我发现有必要将我的所有配置放在validation.xml中,并让Hibernate Validator引导来自该配置。< / p>

您指定的配置适用于特定于春天的事情,但不幸的是,它不适用于Hibernate / Hibernate Validator集成。

答案 1 :(得分:1)

想出来,只需在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;
}