是否可以在嵌套到ConstraintValidator@interface定义中使用依赖项注入?

我创建了需要验证一些数据的自定义注释。

CodebookValidator只是一个普通的类:它没有用@Service@Component进行注释。但是,即使我用@Service进行注释,DI也不起作用...

关于如何在@Autowired中使用ConstraintValidator的任何想法?这是代码段:

@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CodebookValue.CodebookValidator.class)
public @interface CodebookValue {

    Codebook value();

    String message() default "Not valid";

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

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

    class CodebookValidator implements ConstraintValidator<CodebookValue, String> {

        @Autowired
        private CodebookService codebookService; // this won't work it's null at runtime

        private Codebook codebook;

        @Override
        public void initialize(CodebookValue constraintAnnotation) {
            codebook = constraintAnnotation.value();
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext ctx) {
            String translate = codebookService.translate(value, codebook, codebook.getSourceSystem());
            return StringUtils.isEmpty(translate);
        }
    }
}

最佳答案

您可以为自己的Validator bean提供Spring自动装配功能:

@Bean
public Validator validator(final AutowireCapableBeanFactory beanFactory) {

    ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
            .configure()
            .constraintValidatorFactory(new SpringConstraintValidatorFactory(beanFactory))
            .buildValidatorFactory();

    return validatorFactory.getValidator();
}

10-08 01:12