SpringAOP的CGLIB動態代理的底層原理實現
CGLIB動態代理:
CGLIB(Code Generation Library)是一個開源專案!是一個強大的,高效能,高質量的Code生成類庫,它可以在執行期擴充套件Java類與實現Java介面。 Hibernate支援它來實現PO(Persistent Object 持久化物件)位元組碼的動態生成
Hibernate生成持久化類的javassist.
CGLIB生成代理機制:其實生成了一個真實物件的子類.
下載cglib的jar包.
* 現在做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生成代理物件.