歡迎您光臨本站 註冊首頁

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

←手機掃碼閱讀     火星人 @ 2014-03-10 , reply:0

一、攔截器方法

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();
}
@AroundInvoke
public Object myInterceptorMethod2(InvocationContext ic) throws Exception
{
System.out.println(
"myInterceptorMethod2:" ic.getMethod().getName());
obj
= ic.proceed();
}
@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
{
@AroundInvoke
public Object interceptorMethod(InvocationContext ic) throws Exception
{
System.out.println(
"MyInterceptor:" ic.getMethod().getName());
return ic.proceed();
}
}

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

@Stateful
@Interceptors(MyInterceptor.
class)
public class GreeterBean implements Greeter
{
@AroundInvoke
public Object myInterceptorMethod1(InvocationContext ic) throws Exception
{
System.out.println(
"myInterceptorMethod1:" ic.getMethod().getName());
obj
= ic.proceed();
}
@AroundInvoke
public Object myInterceptorMethod2(InvocationContext ic) throws Exception
{
System.out.println(
"myInterceptorMethod2:" ic.getMethod().getName());
obj
= ic.proceed();
}
@Override
public String greet(String name)
{
return "hello " name;
}
}

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

@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方法.


[火星人 ] Eclipse JBoss 5 EJB3開發指南(15):攔截器方法和攔截器類已經有477次圍觀

http://coctec.com/docs/java/show-post-61448.html