0
点赞
收藏
分享

微信扫一扫

使用CGLIB生成代理


知识点

【 


使用前提条件: 


 【 

 /* 

 * 如果这个代理的类没有实现接口就不能使用JDK中的动态代理 

 * 这时需要使用第三方的.jar CGLIB实现代理 

 * 

 */ 

 】 


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 { 

 return methodProxy.invoke(this.targetObject, args); 

 } 

} 

CGLIB可以生成目标类的子类,并重写父类非final修饰符的方法。 



】 


实现步骤: 


第一步:在spring解压包中找到cglib-nodep-2.1_3.jar文件并导入 


第四步:编写PersonServerCGLIB类 

public class PersonServerCGLIB { 

 private IPersonDao personDao; 

 private String name; 


 public PersonServerCGLIB(){} 


 /* 

 * 通过构造器来注入依赖对象 

 */ 

 public PersonServerCGLIB(IPersonDao personDao, String name) { 


 this.name = name; 

 this.personDao = personDao; 


 } 

 public PersonServerCGLIB(String name){ 

 this.name=name; 

 } 


 public String getName() { 

 return name; 

 } 


 public void setName(String name) { 

 this.name = name; 

 } 

 public IPersonDao getPersonDao() { 

 return personDao; 

 } 


 // @Resource(name="mypersonDao") 

 // @Autowired 

 public void setPersonDao(IPersonDao personDao) { 

 this.personDao = personDao; 

 } 

 public void save() { 


 System.out.println("Test CGLIB Proxy"); 

 } 

} 



第三步:编写CGLIB代理类 


public class createCGLIBProxy implements MethodInterceptor{ 

 /* 

 * 如果这个代理的类没有实现接口就不能使用JDK中的动态代理 

 * 这时需要使用第三方的.jar CGLIB实现代理 

 * 

 */ 

 private Object targeObject; 


 public Object createCGLIBProxy(Object targeObject) 

 { 

 this.targeObject=targeObject; 

 Enhancer enhancer=new Enhancer(); 

 //设置父类 这里代理类需要继承这个父类 和JDK实现类似 

 enhancer.setSuperclass(this.targeObject.getClass()); 

 enhancer.setCallback(this); 


 return enhancer.create(); 

 } 


 public Object intercept(Object object, Method method, Object[] arg2, 

 MethodProxy methodProxy) throws Throwable { 


 Object object1=null; 


 PersonServerCGLIB personServer=(PersonServerCGLIB)this.targeObject; 

 if(personServer.getName()!=null || "".equals(personServer.getName())) 

 { 

 object1=methodProxy.invoke(this.targeObject, arg2); 

 } 


 return object1; 

 } 

} 


第四步 :编写单元测 


@Test 

public void TestCGLIBProxy() 

{ 

createCGLIBProxy proxy=new createCGLIBProxy(); 

 //PersonServer personServer=(PersonServer)proxy.createProxyInstance(new PersonServer("liyong")); 


//这里转换为代理类而不是接口原因是这个类没有实现任何接口 


 PersonServerCGLIB personServer=(PersonServerCGLIB)proxy.createCGLIBProxy(new PersonServerCGLIB("liyong")); 

 personServer.save(); 

}

举报

相关推荐

0 条评论