Skip to content

Instantly share code, notes, and snippets.

@JonasGroeger
Created March 27, 2023 21:11
Show Gist options
  • Save JonasGroeger/67ce5ce69302b827544b8190bd3db0de to your computer and use it in GitHub Desktop.
Save JonasGroeger/67ce5ce69302b827544b8190bd3db0de to your computer and use it in GitHub Desktop.
import org.hibernate.validator.HibernateValidator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import javax.validation.Configuration;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorFactory;
import java.util.List;
/**
* A <code>LocalValidatorFactoryBean</code> that first tries to create a validator from a list of custom
* <code>ConstraintValidator</code>s before the default behaviour.
* <p>
* Used in cases where the Custom Validator requires dependencies.
* <p>
* Usage:
*
* <pre>
* MyCustomValidator myCustomValidator = ...
* Validator validator = new CustomLocalValidatorFactoryBean(List.of(myCustomValidator)).getValidator();
*
* validator.validate(myInstance);
* </pre>
*/
public class CustomLocalValidatorFactoryBean extends LocalValidatorFactoryBean {
private final List<ConstraintValidator<?, ?>> customConstraintValidators;
public CustomLocalValidatorFactoryBean(List<ConstraintValidator<?, ?>> customConstraintValidators) {
this.customConstraintValidators = customConstraintValidators;
setProviderClass(HibernateValidator.class);
afterPropertiesSet();
}
@Override
protected void postProcessConfiguration(@NotNull Configuration<?> configuration) {
super.postProcessConfiguration(configuration);
ConstraintValidatorFactory defaultConstraintValidatorFactory =
configuration.getDefaultConstraintValidatorFactory();
configuration.constraintValidatorFactory(
new ConstraintValidatorFactory() {
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
for (ConstraintValidator<?, ?> constraintValidator : customConstraintValidators) {
if (key.equals(constraintValidator.getClass()))
return (T) constraintValidator;
}
return defaultConstraintValidatorFactory.getInstance(key);
}
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
defaultConstraintValidatorFactory.releaseInstance(instance);
}
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment