我想以编程方式向Jersey添加bean验证(没有注释或XML)。我发现:
如何以编程方式创建约束贴图。 http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-programmatic-api
以及如何配置Jersey bean验证。 https://jersey.java.net/documentation/2.8/bean-validation.html#d0e11848
结合它我有类似的东西
public class ValidationConfigurationContextResolver implements ContextResolver<ValidationConfig> {
@Context
private ResourceContext resourceContext;
@Override
public ValidationConfig getContext(Class<?> arg0) {
HibernateValidatorConfiguration configuration = Validation
.byProvider(HibernateValidator.class)
.configure();
ConstraintMapping constraintMapping = configuration.createConstraintMapping();
constraintMapping
.type(SomeBean.class)
.ignoreAllAnnotations()
.property("name", ElementType.FIELD)
.constraint(new SizeDef().max(5).min(2));
configuration.addMapping(constraintMapping);
ValidationConfig config = new ValidationConfig();
config.constraintValidatorFactory(configuration.getDefaultConstraintValidatorFactory());
config.parameterNameProvider(new CustomParameterNameProvider());
return config;
}
/**
* See ContactCardTest#testAddInvalidContact.
*/
private class CustomParameterNameProvider implements ParameterNameProvider {
private final ParameterNameProvider nameProvider;
public CustomParameterNameProvider() {
nameProvider = Validation.byDefaultProvider().configure().getDefaultParameterNameProvider();
}
@Override
public List<String> getParameterNames(final Constructor<?> constructor) {
return nameProvider.getParameterNames(constructor);
}
@Override
public List<String> getParameterNames(final Method method) {
// See ContactCardTest#testAddInvalidContact.
return nameProvider.getParameterNames(method);
}
}
}
但它不起作用。当我调试时,我注意到调用了getContext()方法但是传递了任何无效数据。我需要做什么才能将constraintMapping添加到Jersey。 Jersey ValidationConfig甚至没有扩展javax.validation.Configuration。