jdk动态代理要求委托类需要实现接口,对于一些不实现任何接口的类可以使用cglib动态代理。
使用cglib动态代理需要导入需要的jar包,Spring Core包中已经集成了cglib所需要的jar包。
1、在项目目录下新建一个文件夹,取名lib
2、向lib中添加jar包
3、右击jar包->Build Path->Add to Build Path
//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(); //方法调用
}
}
来源:CSDN
作者:枍汐
链接:https://blog.csdn.net/qq_43581718/article/details/104145201