Spring 3.1 Autowiring does not work inside custom constraint validator

让人想犯罪 __ 提交于 2019-11-30 07:07:24

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" />
...

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!