cglib 的动态代理

接着JDK 的动态代理的内容一起写的

①目标类

public class GirlWaiter{

public void serve() {
System.out.println("上菜");
}
}

public class Advice {
public void smile() {
System.out.println("微笑服务");
}

public void discount() {
System.out.println("打折服务");
}
}

②动态代理代码
public class test {

public static void main(final String[] args) {
final GirlWaiter girlWaiter = new GirlWaiter();//目标对象
final Advice a = new Advice();//增强对象

//返回值 就是动态生成的代理对象 基于cglib
//1.创建增强器
Enhancer enhancer = new Enhancer();
//2.设置父类
enhancer.setSuperclass(GirlWaiter.class);
//3.设置父类
enhancer.setCallback(new MethodInterceptor() {
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
a.smile();
Object invoke = method.invoke(girlWaiter, args);
a.discount();
return invoke;
}
});
//4.创建代理对象
GirlWaiter proxy = (GirlWaiter) enhancer.create();
proxy.serve();
}
}


上一篇:掌握三种代理模式,进军Spring AOP!


下一篇:Cglib动态代理实现原理