1.前言
听到拦截器,预计都不陌生,尤其是在Servlet规范中,充分应用了拦截器的概念。EJB3也提供了拦截器的支持,本质上是轻量级的AOP实现。拦截器能够将多个业务方法中的通用逻辑从业务方法中抽离出来,放在拦截器中实现,从而实现极好的代码复用。
2.EJB中的拦截器
Spring中的AOP实现提供了@Before、@AfterReturning、@AfterThrowing等大量的Annotation,这些注解用于定义功能丰富的增强处理。但是在EJB的拦截器没有打算实现完整的AOP ,仅仅是提供了一个@AroundInvoke Annotation,功能比較有限。
3.拦截器的定义
在EJB中定义拦截器很easy,仅仅须要使用@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修饰该方法。