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修饰该方法。
相关文章推荐
- 浅谈Android数据库版本升级及数据的迁移
- linux中解决SSH连接慢问题
- redis常用操作(持续更新)
- 网络流最大流除草计划
- PHP之正则表达式捕获组与非捕获组(详解)
- oracle笔记之管理员
- 黑马程序员——高新技术---Java基础-GUI编程
- android webView.loadData乱码解决方法
- jQuery选择器
- 限制某个进程只能在某个CPU上运行
- UIKit框架-12.UITableView数据刷新
- Perf -- Linux下的系统性能调优工具,第1部分
- js之 prototype 理解补充
- c语言1
- This web page has a redirect loop
- HDU 5318 (dp+矩阵快速幂优化)
- ubuntu 14.04 安装chrome及给chromium 安装 flash player
- redis配置主从复制
- ldd命令的介绍
- This message is already in use错误及解决