2013-02-11 78 views
1

是否有可能在方法結束時執行一個動作,換言之,當函數控件使用註釋返回給調用者(或者是因爲異常還是正常返回)時?使用註釋退出方法時可以執行操作嗎?

例子:

@DoTaskAtMethodReturn 
public void foo() { 
. 
. 
. 
Method foo Tasks 
. 
. 
. 

return; --------> Background task done by annotation hook here before returning to caller. 
} 
+0

您是否正在使用像Spring或Guice這樣的依賴注入框架?它們提供簡單的AOP功能。 – 2013-02-11 21:18:33

+0

@ CodyA.Ray感謝您的回覆。是的,我正在使用Spring。我不知道AOP,所以我會用它。 – Sumit 2013-02-11 21:55:47

回答

1

你的問題被標記爲Spring-Annotations,所以你顯然使用Spring。有幾個步驟,你想要做什麼用Spring:

Enable AspectJ/AOP-Support在您的配置:

<aop:aspectj-autoproxy/> 

寫一個看點(CF Spring AOP vs AspectJ)使用@After@annotation pointcut

@Aspect 
public class TaskDoer { 

    @After("@annotation(doTaskAnnotation)") 
    // or @AfterReturning or @AfterThrowing 
    public void doSomething(DoTaskAtMethodReturn doTaskAnnotation) throws Throwable { 
    // do what you want to do 
    // if you want access to the source, then add a 
    // parameter ProceedingJoinPoint as the first parameter 
    } 
} 

請請注意以下限制:

  • 除非啓用AspectJ編譯時編織或使用javaagent參數,否則必須通過Spring創建包含foo的對象,即必須從應用程序上下文中檢索它。
  • 沒有附加的依賴關係,只能對通過接口聲明的方法應用方面,即foo()必須是接口的一部分。如果您將cglib用作依賴項,那麼您還可以將方面應用於未通過接口公開的方法。
0

簡短的回答是 「是的,這是可能的」。這是所謂的面向方面編程(AOP)的一部分。基於註釋的AOP的常見用法是@Transactional,用於包裝事務中的所有數據庫活動。

你如何去做取決於你正在構建什麼,你正在使用什麼框架(如果有的話)等等。如果你使用Spring進行依賴注入,這個SO answer有一個很好的例子,或者你可以檢出Spring docs。另一種選擇是使用Guice(我的偏好),它允許easy AOP

相關問題