静态代理实例。
首先定义一个IBuy接口,里面有buy方法。
public interface IBuy {
public void buy();
}
定义一个Buy类,继承IBuy接口。
@Repository("buy")//标注一个DAO组件类
public class Buy implements IBuy {
@Override
public void buy() {
System.out.println("买到书了");
}
}
代理类:
public class ProxyBuy implements IBuy {
IBuy ib;
public ProxyBuy(IBuy ib) {
super();
this.ib = ib;
}
@Override
public void buy() {
GuangGao.show();
ib.buy();
}
}
class GuangGao{
public static void show() {
System.out.println("广告");
}
}
Test:
public class Test {
public static void main(String[] args) {
IBuy ib=new Buy();
ib.buy();
ProxyBuy pb=new ProxyBuy(ib);
pb.buy();
}
}
动态代理实例:
jdk动态代理:
public class JdkProxy implements InvocationHandler{
Object object;
public Object createProxy(Object object) {
this.object = object;
// 1.类加载器
ClassLoader classLoader = JdkProxy.class.getClassLoader();
// 2.被代理对象实现的所有接口
Class[] clazz = object.getClass().getInterfaces();
// 3.使用代理类,进行增强,返回的是代理后的对象
return Proxy.newProxyInstance(classLoader,clazz,this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MyAspect myAspect = new MyAspect();
myAspect.check_Permissions();
Object obj = method.invoke(object, args);
myAspect.log();
return obj;
}
}
class MyAspect{
public void check_Permissions(){
System.out.println("模拟检查权限...");
}
public void log(){
System.out.println("模拟记录日志...");
}
}
Test:
//jdk动态代理
JdkProxy jdkProxy = new JdkProxy();
IBuy ib=new Buy();
IBuy ib1=(IBuy) jdkProxy.createProxy(ib);
ib1.buy();
CGLIB动态代理:
public class CglibProxy implements MethodInterceptor{
public Object createProxy(Object target) {
// 创建一个动态类对象
Enhancer enhancer = new Enhancer();
// 确定需要增强的类,设置其父类
enhancer.setSuperclass(target.getClass());
// 添加回调函数
enhancer.setCallback(this);
// 返回创建的代理类
return enhancer.create();
}
/**
* proxy CGlib根据指定父类生成的代理对象
* method 拦截的方法
* args 拦截方法的参数数组
* methodProxy 方法的代理对象,用于执行父类的方法
*/
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
// TODO Auto-generated method stub
MyAspect myAspect=new MyAspect();
myAspect.check_Permissions();
// 目标方法执行
Object obj=arg3.invokeSuper(arg0, arg2);
myAspect.log();
return obj;
}
}
test:
//CGLIB动态代理
CglibProxy cglibProxy=new CglibProxy();
IBuy ib2=new Buy();
IBuy ib3=(IBuy) cglibProxy.createProxy(ib);
ib3.buy();