我有一个无状态的 Java EE 7 WebService,并且想要使用验证框架来验证传入的数据。这一切都很好。然后我想将任何 ConstraintViolationException 转换为对客户端更友好的东西,并认为装饰器将是理想的选择。
类似于下面的内容。然而,当我部署它时,ValidationInterceptor 抱怨它找不到 Validator 实现。这对我来说是有意义的。我已经能够通过拦截器来使功能正常工作,该拦截器在验证拦截器之前触发,并且可以捕获异常,但是装饰器方法似乎更干净一些。
我在这里缺少什么吗?我的背景主要是Spring,所以对CDI不太熟悉。
Exception while loading the app : CDI deployment failure:WELD-001408: Unsatisfied dependencies for type Validator with qualifiers @Default
at injection point [UnbackedAnnotatedField] @Inject private org.hibernate.validator.cdi.internal.interceptor.ValidationInterceptor.validator
at org.hibernate.validator.cdi.internal.interceptor.ValidationInterceptor.validator(ValidationInterceptor.java:0)
WELD-001475: The following beans match by type, but none have matching qualifiers:
- ValidatorBean [id=org.hibernate.validator.cdi.internal.ValidatorBean_hv]
-- WELD-001408: Unsatisfied dependencies for type Validator with qualifiers @Default
at injection point [UnbackedAnnotatedField] @Inject private org.hibernate.validator.cdi.internal.interceptor.ValidationInterceptor.validator
at org.hibernate.validator.cdi.internal.interceptor.ValidationInterceptor.validator(ValidationInterceptor.java:0)
WELD-001475: The following beans match by type, but none have matching qualifiers:
- ValidatorBean [id=org.hibernate.validator.cdi.internal.ValidatorBean_hv]
]]
@Decorator
public abstract class ValidationDecorator implements Validator {
private static final Logger logger = Logger.getLogger(ValidationDecorator.class.getName());
//the predefine validator bean created by the container
@Inject
@Delegate
private Validator validator;
@Override
public <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {
logger.log(Level.INFO, () -> String.format("Validation decorator validating %s", object));
Set<ConstraintViolation<T>> violations = null;
try {
violations = validator.validate(object, groups);
} catch (ConstraintViolationException ex) {
try {
// build a client friendly message
SOAPFactory factory = SOAPFactory.newInstance();
SOAPFault fault = factory.createFault("A validation error occurred", new QName("ValidationError"));
throw new SOAPFaultException(fault);
} catch (SOAPException e) {
e.printStackTrace();
}
}
return violations;
}
}