Hibernate Validator:拦截无效值

时间:2012-01-13 16:26:23

标签: java annotations guice hibernate-validator

我想设置我的bean以使用Hibernate Validator(用于验证)和Google Guice(用于DI和方法拦截)。<​​/ p>

理想情况下,我想设置一个“失败”验证方法会导致调用方法拦截器的设置:

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显式传递给ClassValidator<T>的{​​{1}}方法来确定通过/失败状态。

所以我需要一个地方来打个电话!我能想到的唯一可行的解决方案是创建我自己的注释(我以前从未完成!),这可能看起来像这样:

getInvalidValues()

然后在Guice @NotNull public @interface AutoValidatingNotNull { // ...?? }

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<Widget> widgetValidator = new ClassValidator<Widget>(); InvalidValue[] badVals = widgetValidator.getInvalidValues(widget); if(badVals.length > 0) handleFailedValidationAndThrowRuntimeExceptionOrSomething(); } }

getFizz()

首先,这只几乎有效:在拦截器的@AutoValidatingNotNull public Fizz getFizz() { return fizz; } 方法中,我如何抓住invoke实例(我们希望的那个)验证)?。有没有办法通过注释传递widget实例?

修改
看起来我不能将widget传递给注释(作为参数)......

其次,这有点令人讨厌。也许我忽略了Hibernate Validator为我提供的一切照顾这一切的东西?还有更好的方法吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

好像你还在使用ClassValidator等人的Hibernate Validator 3.x API。

我建议升级到4.2,其中引入了API for method validation,这正是您所描述的内容。

我可以在GitHub上创建的this project中找到将该API与Google Guice集成所需的胶水代码示例。