【发布时间】:2011-10-18 21:48:54
【问题描述】:
我正在寻找以下是否可能,因为所有初步搜索都没有返回任何结果。
我想使用 Hibernate 的 Validator 注解来验证 bean 方法,我想使用 一些 AOP 框架(Spring、AOP Alliance、AspectJ 等)来拦截带有注解的方法Hibernate Validator 注释的子集(@NotNull、@NotEmpty、@Email 等);然后我希望在遇到 AOP 建议时运行它们。
这可能吗?如果是这样,我很难想象代码是如何工作的。以Spring AOP的MethodInterceptor接口为例:
一、使用Hibernate Validator的bean:
public class SomeBean
{
private String data;
// Hibernate Validator annotation specifying that "data" cannot be an empty
// string.
@NotEmpty
public String getData() { ... } // etc.
}
然后,使用该 bean 的一些代码:
public void someMethod()
{
SomeBean oBean = new SomeBean();
// Validation should fail because we specified that "data" cannot be empty.
oBean.setData("");
}
接下来,当遇到 Hibernate Validator-annotated 方法时要运行的 AOP 建议。
public class ValidationInterceptor implements MethodInterceptor
{
public Object invoke(MethodInvocation invocation)
{
// Here's where we would use Hibernate's validator classes.
// My code example here is wrong, but it gets the point across.
Class targetClass = invocation.getClass(); // Should give me SomeBean.class
ClassValidator<targetClass> oValidator= new ClassValidator<targetClass>();
// Here I need to get a reference to the instance of the offending
// SomeBean object whose data has been set to empty...not sure how!
SomeBean oOffendingBean = getTheBadBeanSomehow();
InvalidValue[] badVals = oValidator.getInvalidValues(oOffendingBean);
}
}
所以,我不仅对 Spring AOP(切入点定义等)配置如何拦截我想要的 Hibernate Validator 注释感到窒息,而且我不仅没有完全掌握如何实现实际的建议(例如,如何从我上面在 cmets 中提到的建议中实例化有问题的SomeBean),但我什至不确定这个解决方案是否可行,Spring 或其他。
提前感谢您在正确方向上的一些温和“推动”!
【问题讨论】:
标签: java hibernate spring aop bean-validation