Spring Autoincrement in validator for Dropwizard
I am using the Validator API to validate my Dropwizard resources.
At this point I need to create my own ConstraintValidator, but my validator needs to be able to connect to the database.
To handle this, I use @Autowire inside my custom ConstraintValidator to expose my customized beans (database).
public class CustomValidator implements ConstraintValidator<CustomAnnotation, String> {
@Autowired private ApplicationContext applicationContext;
@Override
public void initialize(final CustomAnnotation customAnnotation) {
}
@Override
public boolean isValid(final Optional<String> value, final ConstraintValidatorContext context) {
applicationContext.getApplicationName();
return true;
}
}
To get autwiring to work with the validator, I believe I need to use "LocalValidatorFactoryBean".
I configured mine as such:
final LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
factory.setApplicationContext(applicationContext); // preconfigured with my beans
factory.afterPropertiesSet(); // seems to perform the setup of the ConstraintValidatorFactory with applicationContext.getAutowireCapableBeanFactory()
Dropwizard comes with a pre-configured validator in the Environment object.
So, in order for Dropwizard to use a customized Spring validator with injection, I set up the environment with LocalValidatorFactoryBean like this: -
environment.setValidator(factory);
However, rather disappointingly, my @Autowired private ApplicationContext ApplicationContext from my CustomValidator still appears to be null.
Does anyone know where I am going wrong or if there is an easier way?
Edit A bit more information on how this was done.
Ask this in my application: -
final ValidatorFactory constraintValidatorFactory = // custom validator factory
final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
jerseyEnvironment.register(new ValidationConfigurationContextResolver(constraintValidatorFactory, factory));
Then this class replaced the desired validator: -
public class ValidationConfigurationContextResolver implements ContextResolver<ValidationConfig> {
private final ConstraintValidatorFactory constraintValidatorFactory;
private final ValidatorFactory factory;
public ValidationConfigurationContextResolver(final ConstraintValidatorFactory constraintValidatorFactory,final ValidatorFactory factory) {
this.constraintValidatorFactory = constraintValidatorFactory;
this.factory = factory;
}
@Override
public ValidationConfig getContext(final Class<?> type) {
final ValidationConfig config = new ValidationConfig();
config.messageInterpolator(factory.getMessageInterpolator());
config.constraintValidatorFactory(constraintValidatorFactory); // custom constraint validator factory
config.parameterNameProvider(factory.getParameterNameProvider());
config.traversableResolver(factory.getTraversableResolver());
return config;
}
}
source to share
No one has answered this question yet
Check out similar questions: