[英]Intercepting Specific Annotations with Spring AOP
我正在尋找以下方法是否可行,因為所有的初步搜索都沒有回任何表示任何方式的方法。
我想使用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注釋的方法時將運行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注釋,而且我不僅不完全了解如何實現實際建議(例如,如何正如我在上面的注釋中提到的SomeBean
從建議內部實例化有問題的SomeBean
),但是我什至不確定這種解決方案是否可行(Spring還是其他方式)。
預先感謝您在正確的方向上進行了一些輕柔的“輕推”!
您可能對Hibernate Validator 4.2引入的方法驗證功能感興趣,該功能為驗證方法參數和返回值提供支持。
然后,您可以使用Seam Validation ,它將此功能與CDI集成在一起。 如果您想將方法驗證與Spring一起使用,則可以在GitHub上查看該項目, 該項目展示了如何將方法驗證功能與Spring AOP集成(免責聲明:我是該項目以及Seam Validation的作者)。
為了使您的工作例如,你將不得不annote與setter方法的參數@NotEmpty
是這樣的:
public class SomeBean {
private String data;
@NotEmpty
public String getData() { return data; }
public void setData(@NotEmpty String data) { this.data = data; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.