Spring 3.1 Autowiring does not work inside custom constraint validator

前端 未结 2 1616
一整个雨季
一整个雨季 2020-12-30 08:07

I have an issue with bean autowiring inside a custom constraint validator. A constraint validator instance is not given using Spring\'s LocalValidatorFactoryBean. The JSR-3

相关标签:
2条回答
  • 2020-12-30 08:43

    Tito, please check if you can use something like below for Java config:

    @Configuration
    public class SampleConfig {
      ...
    
      @Bean
      public Validator validator() {
        return new LocalValidatorFactoryBean().getValidator();
      }
    
      @Bean
      public MethodValidationPostProcessor mvpp() {
        MethodValidationPostProcessor mvpp = new MethodValidationPostProcessor();
        mvpp.setValidator(validator());
    
        return mvpp;
      }
    
      ...
    }
    

    To reuse the validator bean in a different configuration bean, you can use the @Import annotation.

    0 讨论(0)
  • 2020-12-30 08:46

    Found the problem. The same "validator" bean reference must be used by MethodValidationPostProcessor and mvc:annotation-driven declaration:

    service-context.xml

    <!-- JSR 303 validation -->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
    <bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">
        <property name="validator" ref="validator"/>
    </bean>
        ...
    

    dispatcher-servlet.xml

    ...
    <mvc:annotation-driven validator="validator" />
    ...
    
    0 讨论(0)
提交回复
热议问题