目标类
/**
* @Description cglib动态代理 目标类
* @Date 2021-02-23 9:56
*/
public class Girl {
public void eat(){
System.out.println("yam yam");
}
public void bath(){
System.out.println("xi shua shua");
}
}
cglib的pom.xml
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.4</version>
</dependency>
cglib工厂类
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* @Description cglib动态代理 cglib工厂
* @Date 2021-02-23 9:59
*/
public class CGLibFactory implements MethodInterceptor {
private Object target;
public CGLibFactory() {
super();
}
public CGLibFactory(Object target) {
super();
this.target = target;
}
public Object createProxy() {
//增强器
Enhancer enhancer = new Enhancer();
//创建子类作为代理类 设置父类 目标对象
//通过这一步,其实后面跟静态代理的原理就很像了,只不过执行方法通过反射进行
enhancer.setSuperclass(target.getClass());
//回调给intercept (传参)
enhancer.setCallback(this);
return enhancer.create();
}
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("qian");
//可以对method进行判断
method.invoke(target, args);
System.out.println("hou");
return null;
}
}
执行类
/**
* @Description cglib动态代理 执行类
* @Date 2021-02-23 10:07
*/
public class TestProxy {
public static void main(String[] args) {
Girl proxyGirl = (Girl) new CGLibFactory(new Girl()).createProxy();
proxyGirl.eat();
proxyGirl.bath();
}
}
cglib动态代理可以代理没有继承接口的类,它自己通过Enhancer设置继承,创建目标类的子类,通过回调方法触发intercept,反射执行代理对象的方法。
关键特征是继承MethodInterceptor,实现intercept方法,有一个创建代理子类的Enhancer。
。