【发布时间】:2023-04-10 11:33:01
【问题描述】:
在尝试使用 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; 注释并使用验证逻辑的测试)失败。
【问题讨论】:
-
您是否尝试过像docs.spring.io/spring/docs/current/spring-framework-reference/… 那样配置
LocalValidatorFactoryBean类型的bean? -
@geoand 是的,试过了。如果我只是在没有 WebMvc 部分的情况下启动应用程序上下文,则测试是绿色的。当我尝试将验证器注入弹簧控制器时,测试失败(无法注入验证器)。
-
@geoand 似乎您的解决方案有效。该问题与 Intellij Idea 内部缓存/配置有关。您能否将其发布为答案,以便我接受它
-
很高兴听到它成功了!我将其发布为答案:)
标签: java spring validation spring-boot