在这里我给大家做一个形象的比喻来解释代理,一个女明星要接业务或特殊服务,都是通过她的经纪人来联系,至于价格多少,有些什么服务等等具体操作细节是经济人与客户谈,到这个女明星身上他只要做他本来只能做的东西,其他联系谈判什么的都是经济人在一手处理,所以这个经纪人就相当于一个代理。在java中也是一样!AccountDao交给cglib代理以后那些事前通知,时候通知,环通知都是由代理做的,AccountDao只需要做简单的操作,想相当于女明星只要演戏,唱歌,和XX一样。
说明下:MethodInterceptor接口是spring所带的jar包中的一个的一个接口
首先介绍下这些个类吧。
1,Log类,事后通知,即为做日志。
public class Log { public void doLog(){ System.out.println("做日志"); } }
2,Security类,事前通知,即为业务做分析判断
public class Security { public void doCheck(){ System.out.println("做检查"); } }
3,Transcation类,环通知,即配置事物
public class Transcation { public void beginTransacation(){ System.out.println("开启事务"); } public void closeTransacation(){ System.out.println("关闭事务"); } }
4,CGLIBProxy代理类
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; } }
5,dao层类
public class AccountDao { public void add(){ System.out.println("insert into ...."); } public void delete(){ System.out.println("delete ......"); } }
6,测试类
public class Test { public static void main(String[] args) { AccountDao dao=new AccountDao(); AccountDao proxy=(AccountDao)new CGLIBProxy().createProxyInstance(dao); proxy.add(); } }