我正在查看是否可能執行以下操作,因爲所有初步搜索都沒有返回任何指示方式。使用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或其他。
預先感謝一些溫柔的「輕推」正確的方向!
貢納爾嗨 - 感謝輸入我檢查了所有三個環節現在。我並不偏向任何特定的框架 - 只是對正確的工具感興趣而已!再次感謝 – IAmYourFaja