Spring-Boot如何正确注入javax.validation.Validator

WeM*_*are 39 java validation spring spring-boot

Validator尝试使用JSR-303(hibernate-validator)验证模型时,我在注入spring应用程序bean时遇到问题

我的主要配置类是:

@EnableAutoConfiguration
@EnableWebMvc // <---
@EnableJpaRepositories("com.example")
@EntityScan("com.example")
public class MainConfiguration {
Run Code Online (Sandbox Code Playgroud)

根据javadocs:

/**
 * Provide a custom {@link Validator} instead of the one created by default.
 * The default implementation, assuming JSR-303 is on the classpath, is:
 * {@link org.springframework.validation.beanvalidation.LocalValidatorFactoryBean}.
 * Leave the return value as {@code null} to keep the default.
 */
Validator getValidator();
Run Code Online (Sandbox Code Playgroud)

Hibernate-validator在类路径上.我正在尝试将其注入存储库:

@Repository
public class UserRepositoryImpl implements UserRepositoryCustom    {

    @Autowired
    private Validator validator;
Run Code Online (Sandbox Code Playgroud)

抛出异常:

 No qualifying bean of type [javax.validation.Validator] found for dependency:
Run Code Online (Sandbox Code Playgroud)

更新:

部分解决方法是在主配置类中定义它:

  @Bean
    public Validator validator() {

        return new org.springframework.validation.beanvalidation.LocalValidatorFactoryBean();
    }
Run Code Online (Sandbox Code Playgroud)

但集成测试(需要org.springframework.test.context.web.WebAppConfiguration;注释和使用验证逻辑的测试)失败.

geo*_*and 60

你需要声明一个LocalValidatorFactoryBean类似这样的bean :

<bean id="validator"
    class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
Run Code Online (Sandbox Code Playgroud)

用XML或

@Bean
public javax.validation.Validator localValidatorFactoryBean() {
   return new LocalValidatorFactoryBean();
}
Run Code Online (Sandbox Code Playgroud)

在Java Config中.

Spring文档的这一部分包含所有细节

  • 关于JavaConfig的一个注释.该方法的返回值应为javax.validation.Validator.我会编辑你的答案 (2认同)
  • 当您在主应用程序类上使用@SpringBootApplication时,不应该没有所有这些功能就可以工作。这应该会自动为您的应用包括组件扫描和注释驱动的配置,这将配置正确的验证器。 (2认同)