JSR-303 bean validation with Spring does not kick in

后端 未结 2 2017
夕颜
夕颜 2020-12-18 05:45

I\'ve configured a JSR-303 custom validator following what\'s given in the docs (http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/validation.html), co

相关标签:
2条回答
  • 2020-12-18 06:23
    1. A MethodValidationPostProcessor needs to be configured in addition to the LocalValidatorFactoryBean.
    2. The class to be validated must have a @Validated annotation on it else methods are NOT searched for inline constraint annotations.

      @Configuration
      @ComponentScan(basePackageClasses = {SpringPackageComponentScanMarker.class})
      @EnableAspectJAutoProxy
      public abstract class AppConfig {
      
      @Bean
      public MethodValidationPostProcessor methodValidationPostProcessor() {
          final MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
          methodValidationPostProcessor.setValidator(validator());
      
          return methodValidationPostProcessor;
      }
      
      @Bean
      public LocalValidatorFactoryBean validator() {
          final LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
      
          return localValidatorFactoryBean;
        }
      }
      

    ...

    @Service
    @Validated
    public class SpringBarista extends Barista {
    

    The part of the reference manual that talks about integration with JSR-303 conveniently omits these 2 crucial points without which BV does not kick in. This just caused me 6 hours of debugging and hair tearing where I did everything the doc said but BV would simply not kick in. I finally had to debug through the Spring source code to understand this. There got to be an easier way and I can't be the only one who had this problem. Created a JIRA SPR-11473 for them to update the doc.

    0 讨论(0)
  • 2020-12-18 06:43

    For spring to validation to kick in the blend argument needs a @Valid annotation in front of it.

    Your approach might not work since parameter contraints are not supported by the JSR303.

    Constraint annotations can target any of the following ElementTypes:

    FIELD for constrained attributes

    METHOD for constrained getters

    TYPE for constrained beans

    ANNOTATION_TYPE for constraints composing other constraints

    http://beanvalidation.org/1.0/spec/#constraintsdefinitionimplementation

    0 讨论(0)
提交回复
热议问题