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
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 {
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;
}