栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring中cglib动态代理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring中cglib动态代理

spring中cglib动态代理

生活中案例:租客,中介,房东。

房东:假设拥有收租和退租两个权限,此时房东将自己拥有的权限赋予中介(为代理),租客只能通过中介办理租房业务。

在现实生活中租客可以直接和房东办理租房和退租业务,现在交由中介来完成,整个办理租房的业务通过中介完成,这个过程就叫代理

创建maven项目

引入cglib依赖包

		  
		    cglib
		    cglib
		    3.3.0
		
		
		    org.springframework
		    spring-context
		    5.0.8.RELEASE
		
	
一、cglib直接代理类 1.创建代理类对象
public class Landlord {
	 public void deliver() {
	        try {
	            System.out.println("告知房东出租成功,房东收钱");
	        } catch (Exception e) {
	            e.printStackTrace();
	            System.out.println("出现异常,终止");
	        }
	    }

	    public void out() {
	        try {
	            System.out.println("告知房东,租客退房");
	        } catch (Exception e) {
	            e.printStackTrace();
	            System.out.println("出现异常,终止");
	        }
	    }
}

2.创建MethodInterceptor代理方法
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibMethodInterceptor implements MethodInterceptor {

    // 需要被代理的对象
    private Object target;

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object retVal = null;
        try {
            System.out.println("与中介的交谈");
            // 房东收钱
            Object result = proxy.invokeSuper(obj, args);
            // Object result = method.invoke(target, args);
            System.out.println("达成协议");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出现异常,终止协议");
        }
        return retVal;
    }
}
3.客户端测试代理类
import net.sf.cglib.proxy.Enhancer;
public class CglibTest {
    public static void main(String[] args) throws Exception {
        // 两个new对象和设置对象应该交给spring去做,不应该在这里写的,为了方便理解,就不关联到spring了!
        // 增强类
        CglibMethodInterceptor cglibMethodInterceptor = new CglibMethodInterceptor();
        // 需被代理的对象
        Landlord landlord = new Landlord();
        // 把真实对象放入增强类中,隐藏起来
        cglibMethodInterceptor.setTarget(landlord);

        // 创建Enhancer,用来创建动态代理类
        Enhancer enhancer = new Enhancer();
        // 为代理类指定需要代理的类
        enhancer.setSuperclass(cglibMethodInterceptor.getTarget().getClass());
        // 设置调用代理类会触发的增强类
        enhancer.setCallback(cglibMethodInterceptor);

        // 获取动态代理类对象并返回
        Landlord proxy = (Landlord) enhancer.create();

        // 调用代理类的方法
        proxy.deliver();
        System.out.println("==================");
        proxy.out();
    }
}
4.输出结果:
与中介的交谈
告知房东出租成功,房东收钱
达成协议
==================
与中介的交谈
告知房东,租客退房
达成协议

二、cglib代理类的实现接口 1、创建房东接口
public interface LandlordSerivce {
	//收租
	public void rent();
	//退租
	public void without();

}

2、创建房东接口实现类
public class LandlordSerivceImpl implements LandlordSerivce{

	public void rent() {
		System.out.println("房东收租");
	}

	public void without() {
		System.out.println("房东退租");		
	}

}
3、创建中介代理接口类

注意导包是:import net.sf.cglib.proxy.MethodInterceptor;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;


public class CglibMediaInterceptor implements MethodInterceptor{

	//需要被代理的对象
	private Object target;
	
	
	public void setTarget(Object target) {
		this.target = target;
	}
	
	public Object getTarget() {
		return target;
	}
	
	public Object getProxy(){
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(this.getTarget().getClass());
		enhancer.setCallback(this);
		Object obj =enhancer.create();
		return obj;
	}
	
	
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		Object result = null;
		try {
			 media();//中介自己的相关业务
			 result =	proxy.invokeSuper(obj, args);//房东业务: 处理收租和退租
			 userLogs(method.getName());//记录操作日志
			 System.out.println("==============================="+proxy.getSuperName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	 public void media(){
		 
	    	System.out.println("与中介交谈租房相关事项");
	 }
	 
	 public void userLogs(String method){
		 
		 System.out.println("记录用户操作日志,执行了:"+method+"方法");
	 }
}

4、创建租客客户端测试
public class TenantsClient {
	public static void main(String[] args) {
		
		CglibMediaInterceptor cglib = new CglibMediaInterceptor();
		LandlordSerivce serivce = new LandlordSerivceImpl();
		cglib.setTarget(serivce);
		LandlordSerivce landlordSerivce =(LandlordSerivce)cglib.getProxy();
		landlordSerivce.rent();
		landlordSerivce.without();
		
	}

}
5、输出结果
与中介交谈租房相关事项
房东收租 #被代理的接口
记录用户操作日志,执行了:rent方法 #扩展日志房方法
===============================CGLIB$rent$0
与中介交谈租房相关事项
房东退租 #被代理的接口
记录用户操作日志,执行了:without方法  #扩展日志房方法
===============================CGLIB$without$1

三、cglib代理类生产Class文件 租客客户端测试
public class TenantsClient2 {
	public static void main(String[] args) throws Exception {
		   // System.getProperty("user.dir"):当前项目绝对路径
		String path = "G:/my-study/eclipse-project/ssm-boot-web/target";
		String userDir = "user.dir";
//		saveGeneratedCGlibProxyFiles(System.getProperty(path));
		   System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, path);
		CglibMediaInterceptor cglib = new CglibMediaInterceptor();
		LandlordSerivce serivce = new LandlordSerivceImpl();
		cglib.setTarget(serivce);
		LandlordSerivce landlordSerivce =(LandlordSerivce)cglib.getProxy();
		landlordSerivce.rent();
		landlordSerivce.without();
		
	}
	
	
    public static void saveGeneratedCGlibProxyFiles(String dir) throws Exception {
        Field field = System.class.getDeclaredField("props");
        field.setAccessible(true);
        Properties props = (Properties) field.get(null);
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, dir);//dir为保存文件路径
        props.put("net.sf.cglib.core.DebuggingClassWriter.traceEnabled", "true");
    }

}
输出结果:
//生成.classes文件路径
CGLIB debugging enabled, writing to 'G:/my-study/eclipse-project/ssm-boot-web/target'
与中介交谈租房相关事项
房东收租
记录用户操作日志,执行了:rent方法
===============================CGLIB$rent$0
与中介交谈租房相关事项
房东退租
记录用户操作日志,执行了:without方法
===============================CGLIB$without$1
Cglib源码分析 代理类有三个class类

查看源码如何实现代理

查看第二类就可以知道源码是怎么实现的了。

import java.lang.reflect.Method;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class LandlordSerivceImpl$$EnhancerByCGLIB$$f0007ca2 extends LandlordSerivceImpl implements Factory {
    private MethodInterceptor CGLIB$CALLBACK_0; // 拦截器(增强类)
    private static Object CGLIB$CALLBACK_FILTER;
    private static final Method CGLIB$rent$0$Method;
    private static final MethodProxy CGLIB$rent$0$Proxy;
    private static final Object[] CGLIB$emptyArgs; // 参数
    private static final Method CGLIB$without$1$Method; // 被代理方法
    private static final MethodProxy CGLIB$without$1$Proxy; // 代理方法
    private static final Method CGLIB$equals$2$Method; // 被代理方法
    private static final MethodProxy CGLIB$equals$2$Proxy; // 代理方法

    static void CGLIB$STATICHOOK1() {
        CGLIB$THREAD_CALLBACKS = new ThreadLocal();
        CGLIB$emptyArgs = new Object[0];
        // 代理类
        Class var0 = Class.forName("com.myproxy.landlord.LandlordSerivceImpl$$EnhancerByCGLIB$$f0007ca2");
        // 被代理类
        Class var1;
        // 方法集合
        Method[] var10000 = ReflectUtils.findMethods(new String[]{"rent", "()V", "without", "()V"}, (var1 = Class.forName("com.myproxy.landlord.LandlordSerivceImpl")).getDeclaredMethods());
        // 方法实例赋值给字段(被代理方法)
        CGLIB$rent$0$Method = var10000[0];
        // 方法实例赋值给字段(代理方法)
        CGLIB$rent$0$Proxy = MethodProxy.create(var1, var0, "()V", "rent", "CGLIB$rent$0");
    }

    final void CGLIB$rent$0() {
        super.rent();
    }
    //收组
    public final void rent() {
    	 // 获取拦截器(增强类)
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
        	// 拦截器(增强类)
            var10000.intercept(this, CGLIB$rent$0$Method, CGLIB$emptyArgs, CGLIB$rent$0$Proxy);
        } else {
            super.rent();
        }
    }

    final void CGLIB$without$1() {
        super.without();
    }

    //退租
    public final void without() { 
    	// 获取拦截器(增强类)
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
        	// 拦截器(增强类)
            var10000.intercept(this, CGLIB$without$1$Method, CGLIB$emptyArgs, CGLIB$without$1$Proxy);
        } else {
            super.without();
        }
    }

}

四、总结分析面试题

面试会问:java动态代理和spring cglib动态代理区别有哪些?

不同点:

1.java动态代理只能对类的实现接口代理,不能对类直接代理。

2.cglib动态代理既能对类直接代理也能对实现接口的代理。

3.jdk动态代理实现InvocationHandler接口和invoke()方法

4.cglib动态代理实现MethodInterceptor方法拦截器intercept方法;

5.利用ASM框架,对代理对象类生成的class文件加载进来,通过java反射机制修改其字节码生成子类来处理

相同点:

1.都是使用了java的反射机制来完成。

思考使用场景

1.什么时候使用jdk动态代理和cglib动态代理?

​ 1、目标对象生成了接口 默认用JDK动态代理

​ 2、如果目标对象使用了接口,可以强制使用cglib

​ 3、如果目标对象没有实现接口,必须采用cglib库,Spring会自动在JDK动态代理和cglib之间转换

2、Cglib比JDK快?

​ 1、cglib底层是ASM字节码生成框架,但是字节码技术生成代理类,在JDL1.6之前比使用java反射的效率要高

​ 2、在jdk6之后逐步对JDK动态代理进行了优化,在调用次数比较少时效率高于cglib代理效率

​ 3、只有在大量调用的时候cglib的效率高,但是在1.8的时候JDK的效率已高于cglib

​ 4、Cglib不能对声明final的方法进行代理,因为cglib是动态生成代理对象,final关键字修饰的类不可变只能被引用不能被修改;

3、Spring如何选择是用JDK还是cglib?

​ 1、当bean实现接口时,会用JDK代理模式

​ 2、当bean没有实现接口,用cglib实现

​ 3、可以强制使用cglib(在spring配置中加入)

java动态代理实现案例

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/837099.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号