Hibernate Validator:拦截无效值

我想设置我的bean以使用Hibernate Validator(用于validation)和Google Guice(用于DI和方法拦截)。

理想情况下,我想要一个设置,其中任何“失败”validation的方法将导致调用方法拦截器:

public class Widget { @NotNull public Fizz getFizz() { return fizz; } } public class FailedWidgetInterceptor implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { // This gets executed if Widget's getFizz() returns null... } } 

但看起来Hibernate Validator只允许您通过将对象T显式传递给ClassValidatorgetInvalidValues()方法来确定通过/失败状态。

所以我需要一个地方来打个电话! 我能想到的唯一可行的解决方案是创建我自己的注释(我之前从未做过!),它可能如下所示:

 @NotNull public @interface AutoValidatingNotNull { // ...?? } 

然后在Guice Module

 public class WidgetModule implements Module { public void configure(Binder binder) { binder.bindInterceptor( any(), annotatedWith(AutoValidatingNotNull.class), new ValidatingWidgetInterceptor() ); } } public class ValidatingWidgetInterceptor implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { ClassValidator widgetValidator = new ClassValidator(); InvalidValue[] badVals = widgetValidator.getInvalidValues(widget); if(badVals.length > 0) handleFailedValidationAndThrowRuntimeExceptionOrSomething(); } } 

最后,要更改getFizz()

 @AutoValidatingNotNull public Fizz getFizz() { return fizz; } 

首先,这几乎可以工作:在拦截器的invoke方法中, 我如何获得widget实例(我们希望validation的那个)? 。 有没有办法通过注释传递widget实例?

编辑:
看起来我不能将Object传递给注释(作为参数)……

其次,这有点令人讨厌。 也许我忽略了Hibernate Validator为我提供的所有这些function? 还有更好的方法吗? 提前致谢!

看起来你还在使用ClassValidator等人的Hibernate Validator 3.x API。

我建议升级到4.2,其中引入了用于方法validation的API,这完全符合您的描述。

在我刚刚在GitHub上创建的这个项目中可以找到将该API与Google Guice集成所需的粘合代码的示例。