您的位置:首页 > 其它

EJB学习笔记六(EJB中的拦截器)

2015-07-29 16:21 218 查看
 

 1.前言

听到拦截器,估计都不陌生,尤其是在Servlet规范中,充分应用了拦截器的概念。EJB3也提供了拦截器的支持,本质上是轻量级的AOP实现,拦截器可以将多个业务方法中的通用逻辑从业务方法中抽离出来,放在拦截器中实现,从而实现极好的代码复用。

 2.EJB中的拦截器

Spring中的AOP实现提供了@Before、@AfterReturning、@AfterThrowing等大量的Annotation,这些注解用于定义功能丰富的增强处理,可是在EJB的拦截器没有打算实现完整的AOP
,只是提供了一个@AroundInvoke Annotation,功能比较有限。

 3.拦截器的定义

在EJB中定义拦截器非常简单,只需要使用@AroundInvoke修饰一个拦截器方法即可。

拦截器类

package com.Interceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class HelloInterceptor {

@AroundInvoke
public Object log(InvocationContext ctx) throws Exception {
System.out.println("*** HelloInterceptor intercepting");
long start = System.currentTimeMillis();
try{
if (ctx.getMethod().getName().equals("SayHello")){
System.out.println("*** SayHello已经被调用! *** " );
}
if (ctx.getMethod().getName().equals("Myname")){
System.out.println("*** Myname已经被调用! *** " );
}
return ctx.proceed();
}catch (Exception e) {
throw e;

}finally {
long time = System.currentTimeMillis() - start;
System.out.println("用时:"+ time + "ms");
}
}
}


分析:从上面代码可以看出,这个拦截器并不需要实现任何接口,或者继承什么基类,只要用@AroundInvokeAnnotation标注该拦截器类的方法即可。拦截器方法必须满足如下格式:
public Object XXX(InvocationContext ctx) throws Exception

修饰类

package com.Interceptor;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.interceptor.ExcludeClassInterceptors;
import javax.interceptor.Interceptors;

@Stateless
@Remote (HelloChinaRemote.class)
@Interceptors(HelloInterceptor.class)
public class HelloChinaBean implements HelloChinaRemote {

public String SayHello(String name) {
return name +"你好";
}

//此注解,当拦截的时候,可以排除此方法
@ExcludeClassInterceptors
public String Myname() {
return "我的名字";
}

//直接写在这里也可以
/* @AroundInvoke
public Object log(InvocationContext ctx) throws Exception {
System.out.println("*** HelloInterceptor intercepting");

long start = System.currentTimeMillis();
try{
if (ctx.getMethod().getName().equals("SayHello")){
System.out.println("*** SayHello已经被调用! *** " );
}
if (ctx.getMethod().getName().equals("Myname")){
System.out.println("*** Myname已经被调用! *** " );
}
return ctx.proceed();
}catch (Exception e) {
throw e;

}finally {
long time = System.currentTimeMillis() - start;
System.out.println("用时:"+ time + "ms");
}
}*/
}


 4.小结

1.定义一个拦截器类,没有任何特殊之处,只要使用@AroundInvoke修饰一个具有public Object XXX(InvocationContext ctx) throws Exception签名的方法即可

2.在所有需要被拦截的EJB3的Bean实现类、业务方法上使用@Interceptors修饰

3.如果想将EJB中某个业务方法排除在被拦截之外,使用@ExcludeClassInterceptors修饰该方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: