0

我正在使用 Spring Boot 2.2.4 和 Hibernate 5.4.10。我不明白为什么验证器对象被创建了两次:第一次使用 Spring Boot 上下文,第二次没有它。我试过 javax.persistance.validation.mode=none - 没有任何改变。主要问题是使用 Spring 上下文创建的对象被忽略。注解:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {CustomForBaseEntity.class, CustomForDto.class})
public @interface Custom {
    String message() default "{Your license plate has the wrong format. "
        + "Please don't use special symbols.";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

基类:

abstract class CustomValidator<T> implements ConstraintValidator<LicensePlateValidation, T> {
private Pattern dependency;
@Autowired
    public void setSpringDependency(@Value("${path}") final String dependency) {
        this.dependency = Pattern.compile(dependency);
    }
}

两个派生类看起来一样,所以只有一个:

@Component
public class CustomForBaseEntity extends LicensePlateValidator<Vehicle> {

    @Override
    public boolean isValid(Vehicle vehicle, ConstraintValidatorContext constraintValidatorContext) {
        String licensePlate = vehicle.getLicensePlate();

        return checkLicensePlate(licensePlate, constraintValidatorContext);
   

 }
}

如 Spring Boot 文档中所述,我创建了以下 bean LocalValidatorFactoryBean

@Bean
public Validator validator() {
        return new LocalValidatorFactoryBean();
}
4

0 回答 0