2011-10-18 79 views
1

我正在查看是否可能執行以下操作,因爲所有初步搜索都沒有返回任何指示方式。使用Spring AOP截獲特定註釋

我想使用Hibernate的驗證註釋驗證bean的方法,我想用一些 AOP框架(春,AOP聯盟,AspectJ的等),攔截與休眠的一個子集註解的方法驗證器註釋(@NotNull@NotEmpty,@Email等);然後我希望AOP建議在遇到時運行。

這是可能的嗎?如果是這樣,我很難想象代碼將如何工作。使用Spring AOP的MethodInterceptor接口爲例:

首先,使用Hibernate驗證豆:

public class SomeBean 
{ 
    private String data; 

    // Hibernate Validator annotation specifying that "data" cannot be an empty 
    // string. 
    @NotEmpty 
    public String getData() { ... } // etc. 
} 

然後,使用豆一些代碼:

public void someMethod() 
{ 
    SomeBean oBean = new SomeBean(); 

    // Validation should fail because we specified that "data" cannot be empty. 
    oBean.setData(""); 
} 

接下來,AOP通知是在遇到Hibernate Validator註釋的方法時運行。

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驗證註釋我想要的,也不僅是我不能完全掌握如何實現實際的建議(例如,如何在註釋中實例化來自建議內部的冒犯SomeBean),但我甚至不確定這種解決方案是否可行,Spring或其他。

預先感謝一些溫柔的「輕推」正確的方向!

回答

1

您可能會對Hibernate Validator 4.2中引入的method validation功能感興趣,該功能爲驗證方法參數和返回值提供了支持。

然後,您可以使用Seam Validation,它將此功能與CDI集成在一起。如果您想與Spring一起使用方法驗證,您可以在GitHub上看看this項目,它顯示瞭如何將方法驗證功能與Spring AOP集成(聲明:我是該項目的作者以及Seam驗證的作者)。

爲了使您的工作例如,你將不得不annote setter方法的參數與@NotEmpty這樣的:

public class SomeBean { 

    private String data; 

    @NotEmpty 
    public String getData() { return data; } 

    public void setData(@NotEmpty String data) { this.data = data; } 

} 
+0

貢納爾嗨 - 感謝輸入我檢查了所有三個環節現在。我並不偏向任何特定的框架 - 只是對正確的工具感興趣而已!再次感謝 – IAmYourFaja