gpt4 book ai didi

spring - ConstraintValidator 依赖注入(inject)在类级别验证时会导致 ValidationException

转载 作者:行者123 更新时间:2023-12-04 21:02:25 27 4
gpt4 key购买 nike

ConstraintValidator 中使用依赖注入(inject)时,我遇到了意外的行为。正在类里面进行评估。

实体类:

@Entity
@ValidDemoEntity
public class DemoEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

}

验证注释:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {DemoEntityValidator.class})
public @interface ValidDemoEntity {

String message() default "{some.demo.validator.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};

}

validator :
public class DemoEntityValidator implements ConstraintValidator<ValidDemoEntity, DemoEntity> {

private DemoEntityRepository demoEntityRepository;

public DemoEntityValidator(DemoEntityRepository demoEntityRepository) {
this.demoEntityRepository = demoEntityRepository;
}

@Override
public void initialize(ValidDemoEntity constraintAnnotation) {

}

@Override
public boolean isValid(DemoEntity demoEntity, ConstraintValidatorContext constraintValidatorContext) {
return true;
}
}

测试类:
@SpringBootTest
public class ValidatorInstantiationTest {

private Validator validator;

@Before
public void setUp() throws Exception {
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}

@Test
public void shouldInitiateAndCallDemoEntityValidator() {
DemoEntity demoEntity = new DemoEntity();
validator.validate(demoEntity);
}

}

验证实体会导致:
javax.validation.ValidationException: HV000064: Unable to instantiate ConstraintValidator: com.example.demo.DemoEntityValidator.

并进一步向下堆栈跟踪:
Caused by: java.lang.NoSuchMethodException: com.example.demo.DemoEntityValidator.<init>()

这表明 Hibernate试图启动类(class),而不是让 Spring 来处理。

奇怪的是,依赖注入(inject)适用于字段级别的验证。

代码位于 GitHub .

最佳答案

异常表示没有默认构造函数,因为 Hibernate Validator 尝试实例化您的 validator 。

你必须使用 Spring 。

1 使您的 validator 成为 Spring Bean:

@Component
public class DemoEntityValidator implements ConstraintValidator<ValidDemoEntity, DemoEntity> {

2 注入(inject) Spring 提供的 validator 并使用 SpringRunner 执行您的测试:
@SpringBootTest
@RunWith(SpringRunner.class)
public class ValidatorInstantiationTest {

@Autowired
private Validator validator;

@Test
public void shouldInitiateAndCallDemoEntityValidator() {
DemoEntity demoEntity = new DemoEntity();
validator.validate(demoEntity);
}

}

关于spring - ConstraintValidator 依赖注入(inject)在类级别验证时会导致 ValidationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56791706/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com