Error[8]: Undefined offset: 1111, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

spring中cglib动态代理

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

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

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

创建maven项目

引入cglib依赖包
<dependencies>
		  <dependency>
		    <groupId>cglibgroupId>
		    <artifactId>cglibartifactId>
		    <version>3.3.0version>
		dependency>
		<dependency>
		    <groupId>org.springframeworkgroupId>
		    <artifactId>spring-contextartifactId>
		    <version>5.0.8.RELEASEversion>
		dependency>
	dependencies>
一、cglib直接代理类 1.创建代理类对象
/**
 * cglbi代理类
 * @author jkl
 *
 */
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;
    }

    /**
     * 通过 method 引用实例    Object result = method.invoke(target, args); 形式反射调用被代理类方法,
     * target 实例代表被代理类对象引用, 初始化 CglibMethodInterceptor 时候被赋值 。但是Cglib不推荐使用这种方式
     * @param obj    代表Cglib 生成的动态代理类 对象本身
     * @param method 代理类中被拦截的接口方法 Method 实例
     * @param args   接口方法参数
     * @param proxy  用于调用父类真正的业务类方法。可以直接调用被代理类接口方法
     * @return
     * @throws Throwable
     */
    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、创建房东接口
/**
 * 房东接口
 * @author jkl
 *
 */
public interface LandlordSerivce {
	//收租
	public void rent();
	//退租
	public void without();

}

2、创建房东接口实现类
/**
 * 房东接口实现类
 * @author jkl
 *
 */
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;

/**
 * 中介代理类
 * @author jkl
 *
 */
public class CglibMediaInterceptor implements MethodInterceptor{

	//需要被代理的对象
	private Object target;
	
	/**
	 * 设置代理类对象
	 * @param 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;
	}
	
	/**
     * 通过 method 引用实例    Object result = method.invoke(target, args); 形式反射调用被代理类方法,
     * target 实例代表被代理类对象引用, 初始化 CglibMethodInterceptor 时候被赋值 。但是Cglib不推荐使用这种方式
     * @param obj    代表Cglib 生成的动态代理类 对象本身
     * @param method 代理类中被拦截的接口方法 Method 实例
     * @param args   接口方法参数
     * @param proxy  用于调用父类真正的业务类方法。可以直接调用被代理类接口方法
     * @return
     * @throws Throwable
     */
	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、创建租客客户端测试
/**
 * 租客客户端
 * @author jkl
 *
 */
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/**
 * 租客客户端
 * @author jkl
 *
 */
与中介交谈租房相关事项
房东退租 #被代理的接口
记录用户 *** 作日志,执行了:without方法  #扩展日志房方法
===============================CGLIB$without

三、cglib代理类生产Class文件 租客客户端测试
public
class TenantsClient2 public {
	static void main (String[]) argsthrows 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 ();.
		cglibsetTarget()serivce;LandlordSerivce
		= landlordSerivce (LandlordSerivce).cglibgetProxy();.
		landlordSerivcerent();.
		landlordSerivcewithout();}
		
	/**
     * 设置保存Cglib代理生成的类文件。
     */
	
	public
    static void saveGeneratedCGlibProxyFiles (String) dirthrows Exception Field {
        = field System .class.getDeclaredField("props");.
        fieldsetAccessible(true);Properties
        = props ( Properties). fieldget(null);System
        .setProperty(DebuggingClassWriter.,DEBUG_LOCATION_PROPERTY) dir;//dir为保存文件路径.
        propsput("net.sf.cglib.core.DebuggingClassWriter.traceEnabled","true" );}
    }

//生成.classes文件路径
CGLIB debugging enabled, writing to 'G:/my-study/eclipse-project/ssm-boot-web/target'
与中介交谈租房相关事项
房东收租
记录用户 *** 作日志,执行了:rent方法
===============================CGLIB$rentimport
与中介交谈租房相关事项
房东退租
记录用户 *** 作日志,执行了:without方法
===============================CGLIB$without

输出结果:
.
Cglib源码分析 代理类有三个class类

查看源码如何实现代理

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

. java.langMethodreflect;import.
. net.sf.cglibReflectUtilscore;import.
. net.sf.cglibSignaturecore;import.
. net.sf.cglibCallbackproxy;import.
. net.sf.cglibFactoryproxy;import.
. net.sf.cglibMethodInterceptorproxy;import.
. net.sf.cglibMethodProxyproxy;publicclass

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

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

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

        null )var10000 // 拦截器(增强类) .intercept {
        	(
            var10000this,0Method, CGLIB$rent$,$0Proxy CGLIB$emptyArgs) CGLIB$rent$;$}elsesuper
        . rent {
            ();}}final
        void
    1

    ( ) CGLIB$without$super.without {
        ();}//退租public
    final

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

        null )var10000 // 拦截器(增强类) .intercept {
        	(
            var10000this,1Method, CGLIB$without$,$1Proxy CGLIB$emptyArgs) CGLIB$without$;$}elsesuper
        . 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动态代理实现案例

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 29, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 1112, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

spring中cglib动态代理

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

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

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

创建maven项目

引入cglib依赖包
<dependencies>
		  <dependency>
		    <groupId>cglibgroupId>
		    <artifactId>cglibartifactId>
		    <version>3.3.0version>
		dependency>
		<dependency>
		    <groupId>org.springframeworkgroupId>
		    <artifactId>spring-contextartifactId>
		    <version>5.0.8.RELEASEversion>
		dependency>
	dependencies>
一、cglib直接代理类 1.创建代理类对象
/**
 * cglbi代理类
 * @author jkl
 *
 */
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;
    }

    /**
     * 通过 method 引用实例    Object result = method.invoke(target, args); 形式反射调用被代理类方法,
     * target 实例代表被代理类对象引用, 初始化 CglibMethodInterceptor 时候被赋值 。但是Cglib不推荐使用这种方式
     * @param obj    代表Cglib 生成的动态代理类 对象本身
     * @param method 代理类中被拦截的接口方法 Method 实例
     * @param args   接口方法参数
     * @param proxy  用于调用父类真正的业务类方法。可以直接调用被代理类接口方法
     * @return
     * @throws Throwable
     */
    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、创建房东接口
/**
 * 房东接口
 * @author jkl
 *
 */
public interface LandlordSerivce {
	//收租
	public void rent();
	//退租
	public void without();

}

2、创建房东接口实现类
/**
 * 房东接口实现类
 * @author jkl
 *
 */
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;

/**
 * 中介代理类
 * @author jkl
 *
 */
public class CglibMediaInterceptor implements MethodInterceptor{

	//需要被代理的对象
	private Object target;
	
	/**
	 * 设置代理类对象
	 * @param 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;
	}
	
	/**
     * 通过 method 引用实例    Object result = method.invoke(target, args); 形式反射调用被代理类方法,
     * target 实例代表被代理类对象引用, 初始化 CglibMethodInterceptor 时候被赋值 。但是Cglib不推荐使用这种方式
     * @param obj    代表Cglib 生成的动态代理类 对象本身
     * @param method 代理类中被拦截的接口方法 Method 实例
     * @param args   接口方法参数
     * @param proxy  用于调用父类真正的业务类方法。可以直接调用被代理类接口方法
     * @return
     * @throws Throwable
     */
	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、创建租客客户端测试
/**
 * 租客客户端
 * @author jkl
 *
 */
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/**
 * 租客客户端
 * @author jkl
 *
 */
与中介交谈租房相关事项
房东退租 #被代理的接口
记录用户 *** 作日志,执行了:without方法  #扩展日志房方法
===============================CGLIB$without

三、cglib代理类生产Class文件 租客客户端测试
public
class TenantsClient2 public {
	static void main (String[]) argsthrows 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 ();.
		cglibsetTarget()serivce;LandlordSerivce
		= landlordSerivce (LandlordSerivce).cglibgetProxy();.
		landlordSerivcerent();.
		landlordSerivcewithout();}
		
	/**
     * 设置保存Cglib代理生成的类文件。
     */
	
	public
    static void saveGeneratedCGlibProxyFiles (String) dirthrows Exception Field {
        = field System .class.getDeclaredField("props");.
        fieldsetAccessible(true);Properties
        = props ( Properties). fieldget(null);System
        .setProperty(DebuggingClassWriter.,DEBUG_LOCATION_PROPERTY) dir;//dir为保存文件路径.
        propsput("net.sf.cglib.core.DebuggingClassWriter.traceEnabled","true" );}
    }

//生成.classes文件路径
CGLIB debugging enabled, writing to 'G:/my-study/eclipse-project/ssm-boot-web/target'
与中介交谈租房相关事项
房东收租
记录用户 *** 作日志,执行了:rent方法
===============================CGLIB$rentimport
与中介交谈租房相关事项
房东退租
记录用户 *** 作日志,执行了:without方法
===============================CGLIB$without

输出结果:
.
Cglib源码分析 代理类有三个class类

查看源码如何实现代理

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

. java.langMethodreflect;import.
. net.sf.cglibReflectUtilscore;import.
. net.sf.cglibSignaturecore;import.
. net.sf.cglibCallbackproxy;import.
. net.sf.cglibFactoryproxy;import.
. net.sf.cglibMethodInterceptorproxy;import.
. net.sf.cglibMethodProxyproxy;publicclass

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

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

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

        null )var10000 // 拦截器(增强类) .intercept {
        	(
            var10000this,0Method, CGLIB$rent$,$0Proxy CGLIB$emptyArgs) CGLIB$rent$;$}elsesuper
        . rent {
            ();}}final
        void
    1

    ( ) CGLIB$without$super.without {
        ();}//退租public
    final

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

        null )var10000 // 拦截器(增强类) .intercept {
        	(
            var10000this,1Method, CGLIB$without$,$1Proxy CGLIB$emptyArgs) CGLIB$without$;$}elsesuper
        . 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动态代理实现案例

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 29, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 1113, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

spring中cglib动态代理

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

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

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

创建maven项目

引入cglib依赖包
<dependencies>
		  <dependency>
		    <groupId>cglibgroupId>
		    <artifactId>cglibartifactId>
		    <version>3.3.0version>
		dependency>
		<dependency>
		    <groupId>org.springframeworkgroupId>
		    <artifactId>spring-contextartifactId>
		    <version>5.0.8.RELEASEversion>
		dependency>
	dependencies>
一、cglib直接代理类 1.创建代理类对象
/**
 * cglbi代理类
 * @author jkl
 *
 */
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;
    }

    /**
     * 通过 method 引用实例    Object result = method.invoke(target, args); 形式反射调用被代理类方法,
     * target 实例代表被代理类对象引用, 初始化 CglibMethodInterceptor 时候被赋值 。但是Cglib不推荐使用这种方式
     * @param obj    代表Cglib 生成的动态代理类 对象本身
     * @param method 代理类中被拦截的接口方法 Method 实例
     * @param args   接口方法参数
     * @param proxy  用于调用父类真正的业务类方法。可以直接调用被代理类接口方法
     * @return
     * @throws Throwable
     */
    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、创建房东接口
/**
 * 房东接口
 * @author jkl
 *
 */
public interface LandlordSerivce {
	//收租
	public void rent();
	//退租
	public void without();

}

2、创建房东接口实现类
/**
 * 房东接口实现类
 * @author jkl
 *
 */
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;

/**
 * 中介代理类
 * @author jkl
 *
 */
public class CglibMediaInterceptor implements MethodInterceptor{

	//需要被代理的对象
	private Object target;
	
	/**
	 * 设置代理类对象
	 * @param 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;
	}
	
	/**
     * 通过 method 引用实例    Object result = method.invoke(target, args); 形式反射调用被代理类方法,
     * target 实例代表被代理类对象引用, 初始化 CglibMethodInterceptor 时候被赋值 。但是Cglib不推荐使用这种方式
     * @param obj    代表Cglib 生成的动态代理类 对象本身
     * @param method 代理类中被拦截的接口方法 Method 实例
     * @param args   接口方法参数
     * @param proxy  用于调用父类真正的业务类方法。可以直接调用被代理类接口方法
     * @return
     * @throws Throwable
     */
	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、创建租客客户端测试
/**
 * 租客客户端
 * @author jkl
 *
 */
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/**
 * 租客客户端
 * @author jkl
 *
 */
与中介交谈租房相关事项
房东退租 #被代理的接口
记录用户 *** 作日志,执行了:without方法  #扩展日志房方法
===============================CGLIB$without

三、cglib代理类生产Class文件 租客客户端测试
public
class TenantsClient2 public {
	static void main (String[]) argsthrows 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 ();.
		cglibsetTarget()serivce;LandlordSerivce
		= landlordSerivce (LandlordSerivce).cglibgetProxy();.
		landlordSerivcerent();.
		landlordSerivcewithout();}
		
	/**
     * 设置保存Cglib代理生成的类文件。
     */
	
	public
    static void saveGeneratedCGlibProxyFiles (String) dirthrows Exception Field {
        = field System .class.getDeclaredField("props");.
        fieldsetAccessible(true);Properties
        = props ( Properties). fieldget(null);System
        .setProperty(DebuggingClassWriter.,DEBUG_LOCATION_PROPERTY) dir;//dir为保存文件路径.
        propsput("net.sf.cglib.core.DebuggingClassWriter.traceEnabled","true" );}
    }

//生成.classes文件路径
CGLIB debugging enabled, writing to 'G:/my-study/eclipse-project/ssm-boot-web/target'
与中介交谈租房相关事项
房东收租
记录用户 *** 作日志,执行了:rent方法
===============================CGLIB$rentimport
与中介交谈租房相关事项
房东退租
记录用户 *** 作日志,执行了:without方法
===============================CGLIB$without

输出结果:
.
Cglib源码分析 代理类有三个class类

查看源码如何实现代理

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

. java.langMethodreflect;import.
. net.sf.cglibReflectUtilscore;import.
. net.sf.cglibSignaturecore;import.
. net.sf.cglibCallbackproxy;import.
. net.sf.cglibFactoryproxy;import.
. net.sf.cglibMethodInterceptorproxy;import.
. net.sf.cglibMethodProxyproxy;publicclass

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

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

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

        null )var10000 // 拦截器(增强类) .intercept {
        	(
            var10000this,0Method, CGLIB$rent$,$0Proxy CGLIB$emptyArgs) CGLIB$rent$;$}elsesuper
        . rent {
            ();}}final
        void
    1

    ( ) CGLIB$without$super.without {
        ();}//退租public
    final

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

        null )var10000 // 拦截器(增强类) .intercept {
        	(
            var10000this,1Method, CGLIB$without$,$1Proxy CGLIB$emptyArgs) CGLIB$without$;$}elsesuper
        . 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动态代理实现案例

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 29, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
spring中cglib动态代理_java_内存溢出

spring中cglib动态代理

spring中cglib动态代理,第1张

spring中cglib动态代理

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

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

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

创建maven项目

引入cglib依赖包
<dependencies>
		  <dependency>
		    <groupId>cglibgroupId>
		    <artifactId>cglibartifactId>
		    <version>3.3.0version>
		dependency>
		<dependency>
		    <groupId>org.springframeworkgroupId>
		    <artifactId>spring-contextartifactId>
		    <version>5.0.8.RELEASEversion>
		dependency>
	dependencies>
一、cglib直接代理类 1.创建代理类对象
/**
 * cglbi代理类
 * @author jkl
 *
 */
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;
    }

    /**
     * 通过 method 引用实例    Object result = method.invoke(target, args); 形式反射调用被代理类方法,
     * target 实例代表被代理类对象引用, 初始化 CglibMethodInterceptor 时候被赋值 。但是Cglib不推荐使用这种方式
     * @param obj    代表Cglib 生成的动态代理类 对象本身
     * @param method 代理类中被拦截的接口方法 Method 实例
     * @param args   接口方法参数
     * @param proxy  用于调用父类真正的业务类方法。可以直接调用被代理类接口方法
     * @return
     * @throws Throwable
     */
    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、创建房东接口
/**
 * 房东接口
 * @author jkl
 *
 */
public interface LandlordSerivce {
	//收租
	public void rent();
	//退租
	public void without();

}

2、创建房东接口实现类
/**
 * 房东接口实现类
 * @author jkl
 *
 */
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;

/**
 * 中介代理类
 * @author jkl
 *
 */
public class CglibMediaInterceptor implements MethodInterceptor{

	//需要被代理的对象
	private Object target;
	
	/**
	 * 设置代理类对象
	 * @param 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;
	}
	
	/**
     * 通过 method 引用实例    Object result = method.invoke(target, args); 形式反射调用被代理类方法,
     * target 实例代表被代理类对象引用, 初始化 CglibMethodInterceptor 时候被赋值 。但是Cglib不推荐使用这种方式
     * @param obj    代表Cglib 生成的动态代理类 对象本身
     * @param method 代理类中被拦截的接口方法 Method 实例
     * @param args   接口方法参数
     * @param proxy  用于调用父类真正的业务类方法。可以直接调用被代理类接口方法
     * @return
     * @throws Throwable
     */
	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、创建租客客户端测试
/**
 * 租客客户端
 * @author jkl
 *
 */
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/**
 * 租客客户端
 * @author jkl
 *
 */
与中介交谈租房相关事项
房东退租 #被代理的接口
记录用户 *** 作日志,执行了:without方法  #扩展日志房方法
===============================CGLIB$without

三、cglib代理类生产Class文件 租客客户端测试
public
class TenantsClient2 public {
	static void main (String[]) argsthrows 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 ();.
		cglibsetTarget()serivce;LandlordSerivce
		= landlordSerivce (LandlordSerivce).cglibgetProxy();.
		landlordSerivcerent();.
		landlordSerivcewithout();}
		
	/**
     * 设置保存Cglib代理生成的类文件。
     */
	
	public
    static void saveGeneratedCGlibProxyFiles (String) dirthrows Exception Field {
        = field System .class.getDeclaredField("props");.
        fieldsetAccessible(true);Properties
        = props ( Properties). fieldget(null);System
        .setProperty(DebuggingClassWriter.,DEBUG_LOCATION_PROPERTY) dir;//dir为保存文件路径.
        propsput("net.sf.cglib.core.DebuggingClassWriter.traceEnabled","true" );}
    }

//生成.classes文件路径
CGLIB debugging enabled, writing to 'G:/my-study/eclipse-project/ssm-boot-web/target'
与中介交谈租房相关事项
房东收租
记录用户 *** 作日志,执行了:rent方法
===============================CGLIB$rentimport
与中介交谈租房相关事项
房东退租
记录用户 *** 作日志,执行了:without方法
===============================CGLIB$without

输出结果:
.
Cglib源码分析 代理类有三个class类

查看源码如何实现代理

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

. java.langMethodreflect;import.
. net.sf.cglibReflectUtilscore;import.
. net.sf.cglibSignaturecore;import.
. net.sf.cglibCallbackproxy;import.
. net.sf.cglibFactoryproxy;import.
. net.sf.cglibMethodInterceptorproxy;import.
. net.sf.cglibMethodProxyproxy;publicclass

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

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

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

        null )var10000 // 拦截器(增强类) .intercept {
        	(
            var10000this,0Method, CGLIB$rent$,$0Proxy CGLIB$emptyArgs) CGLIB$rent$;$}elsesuper
        . rent {
            ();}}final
        void
    1

    ( ) CGLIB$without$super.without {
        ();}//退租public
    final

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

        null )var10000 // 拦截器(增强类) .intercept {
        	(
            var10000this,1Method, CGLIB$without$,$1Proxy CGLIB$emptyArgs) CGLIB$without$;$}elsesuper
        . 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动态代理实现案例

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/737605.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存