2011年11月8日 星期二

CDI Interceptor - Context Dependency Injection

CDI 從其標題來看就知道是為了 Servicing Context 以及 Dependency Injection (依賴注入),可參考一下JSR-299的規範說明。

在J2EE 6 中出現的這CDI,到底是要做啥的?

身為一個J2EE Interecptor,肩負的重任是攔截一些商業邏輯流程中的呼叫,亦即 implement cross-cutting ,像是做一些logging or profiling的事情,在這裡主要有幾種的Interceptors:

  • Business Method Interceptor

  • LifeCycle Callback Interceptor

  • Timeout Method Interceotor


拜想當年的 猛虎出閘JDK 5.0 橫空出世所帶來的Annotation,算是徹底的大改了Java app 的開發生態!!

要使用J2EE 6 , EJB 3.0 就不得不先對 Annotation有點基礎認識,但這裡先跳過Annotation 的基礎介紹,以下就來看看在J2EE中的useful anntations:

  • @Target


    • ElementType.TYPE - 只能用在介面或類別上, ex: class, interface , Enum, oreven an annotation

    • ElementType.FIELD - 各式各樣的欄位field

    • ElementTYPE.METHOD - some methods

    • ElementTYPE.PARAMETER - 只能放在method中定義的參數

    • ElementTYPE.CONSTRUCTOR - 建構子使用

    • ElementTYPE.LOCAL_VARIABLE -  only to local variables

    • ElementTYPE.ANNOTATION_TYPE - Annotation types

    • ElementTYPE.PACKAGE - package



這裡來看一個簡單的範例





  • Retention - 用來保留某些特定的annotation用的,可以在定義Annotation型態時,指示Compiler如何處理我的自定義annotation,預設是compiler會將annotation放在class檔案中但不被虛擬機器讀取,而僅用在compiler or 工具程式執行時工資訊。


    • RetentionPolicy.SOURCE

    • RetentionPolicy.CLASS

    • Retention.RUNTIME



再來看個簡單的範例





  • //


在真的要撰寫interceptor之前,我們需要先設置一個所需要的攔截器內容,這裡很簡單,只要把你要的annotation綁釘上一個@InterceptorBinding就可以了,像是這樣:



 

接著,就可以來實作interceptor了,首先先來做的是 Lifecycle callback interceptor

 

 

沒有留言: