且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Spring进行的JSR-303 Bean验证无法启动

更新时间:2022-03-11 01:05:32

  1. 除了LocalValidatorFactoryBean,还需要配置MethodValidationPostProcessor.
  2. 要验证的类上必须带有@Validated批注,否则不会在方法中搜索内联约束批注.

  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 {

参考手册中有关与JSR-303集成的部分方便地忽略了这2个关键点,没有BV就无法发挥这两个关键点.这仅导致我进行了6个小时的调试和撕裂,而我在文档中所做的所有工作却无济于事. BV根本不会发挥作用.我最终不得不通过Spring源代码进行调试才能理解这一点.必须有一种更简单的方法,我不能成为唯一遇到此问题的人.为他们创建了一个JIRA SPR-11473 来更新文档.

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.