【问题标题】:Tests fail with custom jsr validators with @Inject for Spring boot application使用 @Inject 用于 Spring 引导应用程序的自定义 jsr 验证器测试失败
【发布时间】:2026-01-31 16:15:01
【问题描述】:

版本

  1. 休眠验证器 - 5.1.3.Final
  2. spring-boot - 1.2.5.RELEASE
  3. spring-context - 4.1.7.RELEASE

初始应用程序代码是使用 jhipster 生成的。

相关的控制器测试标有以下注释。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest

验证器 bean 未在测试模式下连接。看起来在 web 模式下使用的 ConstraintFactory 实现是 o.s.v.b.SpringConstraintValidatorFactory 而在测试模式下使用的实现是 o.h.v.i.e.c.ConstraintValidatorFactoryImpl,它不负责处理 @Inject 注释。

Web 应用使用 MySQL 作为数据库,而测试使用 H2。

如何将测试配置为使用 SpringConstraintValidatorFactory?

我根据之前的问题和解决方案尝试了以下方法。

  1. 这不是 Hibernate 在保存实体时进行的第二次验证。我通过分析调用堆栈检查了这一点。验证器是从 web 层触发的,在 rest 方法上带有 @Valid 注释。

  2. 将此添加到 application.yml 文件没有帮助。我猜这是为了休眠保存/更新验证。就我而言,是在 web 层进行验证。

spring.jpa.properties.javax.persistence.validation.mode=none

谢谢。

【问题讨论】:

  • 请解释一下 -ve 票。我想解决这个问题中的任何问题。谢谢。

标签: spring-boot junit4 bean-validation jhipster


【解决方案1】:

因此,就我而言,我编写了几个需要自动装配的自定义验证器(在此 https://docs.jboss.org/hibernate/validator/4.0.1/reference/en/html/validator-customconstraints.html 之后)。我在 @Constraint 注释中提供了验证器类。

@Constraint(validatedBy = MyCheckValidator.class)

我看到在标准验证器中,诸如 @NotNull 等 validBy 被填充为一个空数组。

在我的验证器中,我将 validBy 字段更改为 {},这一切都开始工作了。我不知道为什么。

@Constraint(validatedBy = {})

如果有人能解释更详细的细节将不胜感激。

【讨论】: