我正在使用Validator API来验证我的Dropwizard资源。
此时我需要创建一个自定义的ConstraintValidator - 但我的验证器必须能够连接到数据库。
为了解决这个问题,我在自定义的ConstraintValidator中使用@Autowire来提供我配置的bean(数据库)。
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;
}
}
为了让autowiring与验证器一起工作,我相信我必须使用'LocalValidatorFactoryBean'。
我已经配置了我的: -
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附带了一个在Environment对象中预先配置的验证器。
因此,为了确保Dropwizard使用Spring配置的验证器和注入,我使用LocalValidatorFactoryBean设置环境,如下所示: -
environment.setValidator(factory);
然而,令人沮丧的是,来自我的CustomValidator的@Autowired私有ApplicationContext applicationContext仍显示为null。
有谁知道我在哪里出错或者有更简单的方法吗?
修改有关如何完成的更多信息。
在我的应用程序中进行设置: -
final ValidatorFactory constraintValidatorFactory = // custom validator factory
final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
jerseyEnvironment.register(new ValidationConfigurationContextResolver(constraintValidatorFactory, factory));
然后使用此类替换所需的验证器: -
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;
}
}