在尝试使用JSR-303(hibernate-validator)验证模型时,我在将Validator
注入spring应用程序bean时遇到了问题
我的主要配置类是:
@EnableAutoConfiguration
@EnableWebMvc // <---
@EnableJpaRepositories("com.example")
@EntityScan("com.example")
public class MainConfiguration {
根据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();
Hibernate-validator在类路径上。 我试图将其注入存储库:
@Repository
public class UserRepositoryImpl implements UserRepositoryCustom {
@Autowired
private Validator validator;
抛出异常:
No qualifying bean of type [javax.validation.Validator] found for dependency:
更新
部分解决方法是在主配置类中定义它:
@Bean
public Validator validator() {
return new org.springframework.validation.beanvalidation.LocalValidatorFactoryBean();
}
但集成测试(需要org.springframework.test.context.web.WebAppConfiguration;
注释和使用验证逻辑的测试)失败。
答案 0 :(得分:53)
您需要声明类似LocalValidatorFactoryBean
的bean:
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
以XML或
@Bean
public javax.validation.Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
在Java Config中。
This部分Spring文档包含所有细节