Spring-Boot 如何正确地注入 javax.validation.Validator
2022-08-31 20:35:38
在尝试使用JSR-303(休眠验证器)验证模型时,我在将注入弹簧应用程序bean时遇到问题Validator
我的主要配置类是:
@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();
休眠验证器位于类路径上。我正在尝试将其注入存储库:
@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;