cglib动态代理

依然范特西╮ 提交于 2020-02-03 01:51:12

jdk动态代理要求委托类需要实现接口,对于一些不实现任何接口的类可以使用cglib动态代理。

使用cglib动态代理需要导入需要的jar包,Spring Core包中已经集成了cglib所需要的jar包。
1、在项目目录下新建一个文件夹,取名lib
2、向lib中添加jar包
3、右击jar包->Build Path->Add to Build Path
导入jar包

//Human类,不实现任何接口
class Human{
	public void eat() {
		System.out.println("吃");
	}	
	//创建代理对象
	public Human createProxy() {
		MyInterceptor cp=new MyInterceptor();
		//创建动态类对象
		Enhancer eh=new Enhancer();
		//将需要增强的类设置为其父类
		eh.setSuperclass(this.getClass());
		//设置代理逻辑对象,即由这个对象(cp)来处理对真实对象方法的调用
		eh.setCallback(cp);
		//返回代理对象
		return (Human)eh.create();
	}	
}
class MyInterceptor implements MethodInterceptor{
	//通过intercept方法完成对真实对象方法的调用
	@Override
	public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
		System.out.println("before");
		Object obj=methodProxy.invokeSuper(proxy, args);
		return obj;
	}	
}
public class Test {
	public static void main(String []args) {
		Human human=new Human();         //创建真实对象
		Human proxy=human.createProxy(); //创建代理对象
		proxy.eat();                     //方法调用
	}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!