學 AOP 的過程裡,撞牆幾乎是必經之路。更麻煩的是,把錯誤訊息丟進搜尋引擎,看到的答案往往抄來抄去、沒人真正推敲過。於是我把實作時踩到的兩個典型錯誤整理下來,方便日後翻查。
關鍵訊息是 can't find referenced pointcut update:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IStudentMgr' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut update ...
這代表切入點的語法不合法。錯誤寫法把類別與方法直接寫成一串:
@AfterReturning("com.trs.components.mgr.StudentMgr.update()")
正確的寫法必須用 execution 表達式把方法包起來:
@AfterReturning("execution(* com.trs.components.mgr.StudentMgr.update(..))")
關鍵訊息是 formal unbound in pointcut:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IStudentMgr' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut ...
問題出在使用 @AfterReturning 時沒有宣告返回參數,但通知方法本身卻要求傳入一個參數(例如 _result)。只要通知方法想接參數,就必須在注解裡明確聲明。
錯誤寫法:
@AfterReturning("execution (* com.trs.components.mgr.StudentMgr.update(..))")
public void writeAge(Object _result) {
System.out.println("result::" + _result);
System.out.println("我是另外一個切面,年齡::" + 23);
}
正確寫法(注意 returning 屬性宣告了名為 _result 的返回變數):
@AfterReturning(pointcut = "execution (* com.trs.components.mgr.StudentMgr.update*(..))", returning = "_result")
public void writeAge(Object _result) {
System.out.println("result::" + _result);
System.out.println("我是另外一個切面,年齡::" + 23);
}
把這兩處寫法定住,AOP 啟動階段最常見的 BeanCreationException 基本就能避開。剩下的問題多半出在代理型別轉換或套件掃描範圍,那是另一段故事了。