简单模拟spring cglib代理
spring使用了两种代理模式,一种是jdk动态代理,另有一种就是我下面将要还原的cglib代理。在这里我向大家推荐一个具体分析jdk动态代理和cglib的区别和优缺点的博客:http://hbzwt.iteye.com/blog/909147,具体大家可以参照他写的,个人感觉写的蛮好。
在这里我给大家做一个形象的比喻来解释代理,一个女明星要接业务或特殊服务,都是通过她的经纪人来联系,至于价格多少,有些什么服务等等具体操作细节是经济人与客户谈,到这个女明星身上他只要做他本来只能做的东西,其他联系谈判什么的都是经济人在一手处理,所以这个经纪人就相当于一个代理。在java中也是一样!AccountDao交给cglib代理以后那些事前通知,时候通知,环通知都是由代理做的,AccountDao只需要做简单的操作,想相当于女明星只要演戏,唱歌,和XX一样。
说明下:MethodInterceptor接口是spring所带的jar包中的一个的一个接口
首先介绍下这些个类吧。
1,Log类,事后通知,即为做日志。
public class Log {public void doLog(){System.out.println("做日志");}}
public class Security {public void doCheck(){System.out.println("做检查");}}
public class Transcation {public void beginTransacation(){System.out.println("开启事务");}public void closeTransacation(){System.out.println("关闭事务");}}
public class CGLIBProxy implements MethodInterceptor {private Object targetObject;//代理的目标对象public Object createProxyInstance(Object targetObject){this.targetObject = targetObject;Enhancer enhancer = new Enhancer();//该类用于生成代理对象enhancer.setSuperclass(this.targetObject.getClass());//设置父类enhancer.setCallback(this);//设置回调用对象为本身return enhancer.create();}public Object intercept(Object proxy, Method method, Object[] args,MethodProxy methodProxy) throws Throwable {Log log=new Log();//事后通知Security security=new Security();//事前通知Transcation tx=new Transcation();//环通知security.doCheck();tx.beginTransacation();Object obj=methodProxy.invoke(this.targetObject, args);tx.closeTransacation();log.doLog();return obj;}}
public class AccountDao {public void add(){System.out.println("insert into ....");}public void delete(){System.out.println("delete ......");}}
public class Test {public static void main(String[] args) { AccountDao dao=new AccountDao(); AccountDao proxy=(AccountDao)new CGLIBProxy().createProxyInstance(dao); proxy.add(); }}