spring源码学习之【准备】cglib动态代理例子
一:委托者
1 package com.yeepay.porxy.cglib.test; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 /** 7 * 目标类,(委托类) 8 * @author shangxiaofei 9 * 10 */ 11 public class PaymentServer { 12 13 public Map<String, String> payMoney(String name,Integer money){ 14 System.out.println("paymentServer.payMoney()付钱=========>名字【"+name+"】,money=【"+money+"】"); 15 Map<String, String> map=new HashMap<String, String>(); 16 map.put("result", "已经完成付钱"); 17 return map; 18 } 19 }
二:增强者(代理类)
1 package com.yeepay.porxy.cglib.test; 2 3 import java.lang.reflect.Method; 4 5 import net.sf.cglib.proxy.MethodInterceptor; 6 import net.sf.cglib.proxy.MethodProxy; 7 /** 8 * 增强类 9 * @author shangxiaofei 10 * 11 */ 12 public class PoxyForService implements MethodInterceptor{ 13 14 @Override 15 public Object intercept(Object arg0, Method arg1, Object[] arg2,MethodProxy arg3) throws Throwable { 16 // 增强功能的代码 17 System.out.println("PoxyForService.intercept(方法执行前执行========>向统计发送消息)"); 18 if(arg2!=null&&arg2.length>0){ 19 for(int i=0;i<arg2.length;i++){ 20 System.out.println("PoxyForService.intercept()发送的参数内容====>"+arg2[i]); 21 } 22 } 23 24 25 //执行方法内容 26 Object object=arg3.invokeSuper(arg0, arg2); 27 28 29 System.out.println("PoxyForService.intercept(方法执行后执行=======>计算时间)"); 30 return object; 31 } 32 33 34 35 }
三:创造代理的工厂类
1 package com.yeepay.porxy.cglib.test; 2 3 import net.sf.cglib.proxy.Enhancer; 4 5 /** 6 * 代理实现工厂类 7 * @author shangxiaofei 8 * 9 */ 10 public class PoxyFactory { 11 public static PaymentServer getPaymentServer(){ 12 // Cglib 核心类,生成代理对象 13 Enhancer enhancer= new Enhancer(); 14 // 为核心类对象中放入需要代理的委托类的类对象 15 enhancer.setSuperclass(PaymentServer.class); 16 // 为核心类对象中放入增强功能的类对象 17 enhancer.setCallback(new PoxyForService()); 18 // 从核心类对象中获取委托类的代理对象 19 Object object=enhancer.create(); 20 21 return (PaymentServer) object; 22 } 23 }
四:测试类
1 package com.yeepay.porxy.cglib.test; 2 3 import java.util.Map; 4 /** 5 * 测试类 6 * @author shangxiaofei 7 * 8 */ 9 public class TestController { 10 11 private PaymentServer paymentServer=PoxyFactory.getPaymentServer(); 12 13 public void payment(){ 14 System.out.println("TestController.payment()开始"); 15 Map<String, String> map=paymentServer.payMoney("怪物雷克", 100); 16 System.out.println("TestController.payment()结束===>"+map.get("result")); 17 } 18 19 20 /** 21 * TestController.payment()开始 22 * PoxyForService.intercept(方法执行前执行========>向统计发送消息) 23 * PoxyForService.intercept()发送的参数内容====>怪物雷克 24 * PoxyForService.intercept()发送的参数内容====>100 25 * paymentServer.payMoney()付钱=========>名字【怪物雷克】,money=【100】 26 * PoxyForService.intercept(方法执行后执行=======>计算时间) 27 * TestController.payment()结束===>已经完成付钱 28 * @param args 29 */ 30 public static void main(String[] args) { 31 TestController testController=new TestController(); 32 testController.payment(); 33 } 34 }