SpringAOP的CGLIB动态代理的底层原理实现

来源:互联网 发布:java中线程之间的通信 编辑:程序博客网 时间:2024/04/30 05:49

CGLIB动态代理:

CGLIB(Code Generation Library)是一个开源项目!是一个强大的,高性能,高质量的Code生成类库,它可以在运行期扩展Java类与实现Java接口。Hibernate支持它来实现PO(Persistent Object持久化对象)字节码的动态生成

Hibernate生成持久化类的javassist.

CGLIB生成代理机制:其实生成了一个真实对象的子类.

 

下载cglibjar.

* 现在做cglib的开发,可以不用直接引入cglib的包.已经在spring的核心中集成cglib.

 

public class CGLibProxy implements MethodInterceptor{

private ProductDao productDao;

 

public CGLibProxy(ProductDao productDao) {

super();

this.productDao = productDao;

}

public ProductDao createProxy(){

// 使用CGLIB生成代理:

// 1.创建核心类:

Enhancer enhancer = new Enhancer();

// 2.为其设置父类:

enhancer.setSuperclass(productDao.getClass());

// 3.设置回调:

enhancer.setCallback(this);

// 4.创建代理:

return (ProductDao) enhancer.create();

}

public Object intercept(Object proxy, Method method, Object[] args,

MethodProxy methodProxy) throws Throwable {

if("add".equals(method.getName())){

System.out.println("日志记录==============");

Object obj = methodProxy.invokeSuper(proxy, args);

return obj;

}

return methodProxy.invokeSuper(proxy, args);

}

}

Spring框架结论

如果这个类没有实现任何接口,使用CGLIB生成代理对象.

0 0