天天看點

eclipse + JBoss 5 + EJB3開發指南(15):攔截器方法和攔截器類

本文為原創,如需轉載,請注明作者和出處,謝謝!

一、攔截器方法

    EJB3可以通過攔截器對Bean方法進行攔截和覆寫。這有些象AOP中的around。通過AOP的around方法,可以修改被攔截方法的傳回值、參數值,甚至可以取消被攔截方法的執行。EJB3的攔截器可以用在無狀态Session Bean、有狀态Session Bean和消息驅動Bean(MDB)的方法中。實作攔截器的最簡單的方法是使用攔截器方法。也就是說,隻要在目前的Bean中使用@AroundInvoke對某個方法進行注釋(關于攔截器的類都在javax.interceptor包中),那麼這個方法就會變成攔截器方法,該攔截器方法會攔截目前Bean中的所有方法。實作過程如下:

@Stateful

public class GreeterBean implements Greeter

{

    @AroundInvoke

    public Object myInterceptorMethod1(InvocationContext ic) throws Exception

    {

        System.out.println("myInterceptorMethod1:" + ic.getMethod().getName());

        obj = ic.proceed();    

    }

    public Object myInterceptorMethod2(InvocationContext ic) throws Exception

        System.out.println("myInterceptorMethod2:" + ic.getMethod().getName());

    @Override

    public String greet(String name)

        return "hello " + name;

}

    上面的Stateful Session Bean中定義了兩個攔截器方法和一個Bean方法。當用戶端調用greet方法時,EJB容器會先調用myInterceptorMethod1方法,然後會調用myInterceptorMethod2方法,最後會調用greet方法。使用攔截器方法時要注意如下幾點:

1.  攔截器方法必須有一個傳回值,傳回值類型是Object。

2.  攔截器方法隻能有一個參數,而且該參數類型必須是javax.interceptor.InvocationContext。

3.  隻有調用InvocationContext接口的proceed方法,EJB容器才會調用下一個攔截器方法或被攔截的Bean方法。

4.  由于proceed方法要求抛出一個Exception異常,是以,攔截器方法必須抛出一個Exception異常,或在攔截器方法中使用try...catch來捕捉proceed方法抛出的異常。

二、攔截器類

    有一些攔截器方法會攔截器不同Bean中的方法,在這種情況下,需要将攔截器方法放在一個單獨的類中。這個類就叫攔截器類。下面是一個攔截器類的代碼:

package service;

import javax.interceptor.AroundInvoke;

import javax.interceptor.InvocationContext;

public class MyInterceptor

    public Object interceptorMethod(InvocationContext ic) throws Exception

        System.out.println("MyInterceptor:" + ic.getMethod().getName());

        return ic.proceed();

    為了使用該攔截器類,需要在SessionBean或MDB中使用@Interceptors來指定要使用的攔截器類。代碼如下:

@Interceptors(MyInterceptor.class)

    如果有多個攔截器類,可以使用如下的代碼來指定這些攔截器類:

@Interceptors({MyInterceptor.class, MyInterceptor1.class})

    如果指定了多個攔截器類和攔截器方法,就涉及到一個調用順序的問題。EJB容器會先調用攔截器類中的攔截器方法、如果有多個攔截器類被指定,按指定的順序進行調用。也就是說,MyInterceptor類中的攔截器方法會最先被調用,然後是MyInterceptor1類中的攔截器方法。最後會調用在Bean中定義的攔截器方法(myInterceptorMethod1和myInterceptorMethod2)。

    在預設情況下,攔截器類将攔截所有的Bean方法,但可以使用@ExcludeClassInterceptors注釋來阻止攔截器對某個Bean方法進行攔截。如在GreeterBean類中還有一個getValue方法,那麼阻止該方法被攔截的代碼如下:

@ExcludeClassInterceptors

public String getValue()

    return "abcd";

    使用@ExcludeClassInterceptors隻能阻止攔截器類中的攔截器方法對Bean方法的攔截,而在Bean中定義的攔截器方法仍然會攔截Bean方法。

<a href="http://www.eoeandroid.com/forumdisplay.php?fid=4">國内最棒的Google Android技術社群(eoeandroid),歡迎通路!</a>

繼續閱讀