Injecting Spring Dependencies into ConstrantValidator

前端 未结 1 1805
春和景丽
春和景丽 2021-01-29 08:15

I\'m using Bean Validation. I have a custom validator @MyValidator that needs to look up a value with an injected Spring managed DAO object. How can I get access t

相关标签:
1条回答
  • 2021-01-29 09:05

    The minimum setup for @Autowired to work properly in ConstraintValidator implementation is to have this bean in a Spring @Configuration:

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

    This allows any beans, including ApplicationContext, to be injected directly into a ConstraintValidator:

    @Constraint(validatedBy = DemoValidator.class)
    public @interface DemoAnnotation {
        // ...
        Class<?> beanClass();
    }
    
    public class DemoValidator implements ConstraintValidator<DemoAnnotation, String> {
    
        private final ApplicationContext applicationContext;
    
        private Object bean;
    
        @Autowired
        public DemoValidator(ApplicationContext applicationContext) {
            this.applicationContext = applicationContext;
        }
    
        @Override
        public void initialize(DemoAnnotation constraint) {
            Class<?> beanClass = constraint.beanClass();
            bean = applicationContext.getBean(beanClass);
        }
    
        @Override
        public boolean isValid(String obj, ConstraintValidatorContext context) {
            return !obj.isEmpty();
        }
    }
    

    Demo

    For a really flexible validation solution I would recommend Jakub Jirutka's Bean Validator utilizing Spring Expression Language (SpEL) which allows things like:

    public class Sample {
    
        @SpELAssert("@myService.calculate(#this) > 42")
        private int value;
    }
    
    0 讨论(0)
提交回复
热议问题