静态代理与动态代理的使用。

静态代理实例。
首先定义一个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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值