2012-04-20 46 views
10

說我有一個像這樣的方法:Spring AOP的切入點進行註釋參數

public void method(@CustomAnnotation("value") String argument) 

有一個切入點表達式,可以選擇與@CustomAnnotation標註的參數的所有方法?如果有的話,我可以訪問的方式去「價值」的說法?

回答

14

在選擇你的論點:

@Before("execution(* *(@CustomAnnotation (*)))") 
public void advice() { 
System.out.println("hello"); 
} 

裁判:http://forum.springsource.org/archive/index.php/t-61308.html

在獲得註釋PARAM:

MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 
Method method = signature.getMethod(); 
Annotation[][] methodAnnotations = method.getParameterAnnotations(); 

會得到你,你可以迭代,並使用instanceof來找到註解你的約束註釋。我知道這是hacky,但afaik這是目前唯一支持的方式。

+2

您需要的註釋後,即添加一個空格@ CustomAnnotation(*) – 2013-12-04 02:02:36

1

從春天文檔:

@Before("@annotation(myAnnotation)") 
public void audit(Auditable myAnnotation) { 
    AuditCode code = auditable.value(); 
    // ... 
} 

這對我來說,工作得很好,沒有任何需要操作的方法簽名。

注意:如果您使用的是已命名的切入點,因爲切入點名稱可能會被重載,您必須提供匹配的(參數名稱和順序)簽名。

@Before("goodAdvise(myAnnotation)") 
public void audit(Auditable myAnnotation) { 
    String value = auditable.value(); 
    // ... 
} 

@Pointcut("@annotation(myAnnotation)") 
public void goodAdvise(Auditable myAnnotation) { 
    //empty 
} 
+0

「@ annotation」切入點引用方法上的註釋,而不是參數。 – 2016-02-08 14:21:08

0

如果您在方法有一個以上的參數,你也應該用兩個點的mathing任意數量的參數(零個或多個)

@Before("execution(* *(@CustomAnnotation (*), ..))") 
public void advice() { 
    System.out.println("hello"); 
}