【问题标题】:Intercepting Specific Annotations with Spring AOP使用 Spring AOP 拦截特定注解
【发布时间】: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


    【解决方案1】:

    您可能对 Hibernate Validator 4.2 引入的 method validation 功能感兴趣,该功能支持验证方法参数和返回值。

    然后您可以使用Seam Validation,它将此功能与 CDI 集成。如果您想将方法验证与 Spring 一起使用,您可以查看 GitHub 上的 this 项目,该项目展示了如何将方法验证功能与 Spring AOP 集成(免责声明:我是该项目以及 Seam Validation 的作者)。

    要使您的示例正常工作,您必须使用 @NotEmpty 注释 setter 方法的参数,如下所示:

    public class SomeBean {
    
        private String data;
    
        @NotEmpty
        public String getData() { return data; }
    
        public void setData(@NotEmpty String data) { this.data = data; }
    
    }
    

    【讨论】:

    • 您好 Gunnar - 感谢您的输入,我现在正在查看所有三个链接。我不偏爱任何特定的框架——只对正确的工具感兴趣!再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多