11、Spring5.x源码之旅十一模拟Spring的CGLIB动态代理生成字节码

  • 模拟生成的代理字节码(感受下CGLIB)
    • 测试代码
  • MyBeanFactoryAwareGeneratorStrategy扩展策略
  • 被代理类
  • 结果:
    • 增强的方法:

模拟生成的代理字节码(感受下CGLIB)

前一篇讲了如果配置类有full属性的话,spring会对他进行cglib动态代理增强,而且会加入拦截器,会实现接口,本篇我们就模拟一下spring怎么做的。

测试代码

我们按照spring的做法,因为很多类是内部里,无法拿出来用,所以一部分我用反射来进行,字节码生成策略我复制出来改了下。我们的测试代码:

  	@Test
    public void cglibTest() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
   
     
        //反射出ConfigurationClassEnhancer,并创建实例
        Class<?> configurationClassEnhancerClass = Class.forName("org.springframework.context.annotation.ConfigurationClassEnhancer");
        Constructor constructor = configurationClassEnhancerClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        Object configurationClassEnhancer = constructor.newInstance();

        //获取属性callbackFilter
        Field callbackFilterField = configurationClassEnhancerClass.getDeclaredField("CALLBACK_FILTER");
        callbackFilterField.setAccessible(true);
        CallbackFilter callbackFilter = (CallbackFilter) callbackFilterField.get(configurationClassEnhancer);

        //反射ConditionalCallbackFilter类
        Class<?> ConditionalCallbackFilter = Class.forName("org.springframework.context.annotation.ConfigurationClassEnhancer$ConditionalCallbackFilter");
        //获取getCallbackTypes方法
        Method getCallbackTypesMethod = ConditionalCallbackFilter.getDeclaredMethod("getCallbackTypes");
        getCallbackTypesMethod.setAccessible(true);
        
        
        //反射出EnhancedConfiguration接口
        Class<?> enhancedConfiguration = Class.forName("org.springframework.context.annotation.ConfigurationClassEnhancer$EnhancedConfiguration");

        //创建增强类
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(MyConfig.class);//设置目标类
        enhancer.setInterfaces(new Class<?>[]{
   
     enhancedConfiguration});//设置要实现的接口
        enhancer.setUseFactory(false);
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        enhancer.setStrategy(new MyBeanFactoryAwareGeneratorStrategy(this.getClass().getClassLoader()));//生成自定义的策略
        //过滤器
        enhancer.setCallbackFilter(callbackFilter);
        //过滤器类型
        enhancer.setCallbackTypes((Class[]) getCallbackTypesMethod.invoke(callbackFilter));
        //创建代理类
        Class proxy = enhancer.createClass();
        System.out.println(proxy);
    }

MyBeanFactoryAwareGeneratorStrategy扩展策略

我们的扩展策略,因为我要把他的二进制字节码保存到本地查看,所以要扩展,而且我把增加的属性名改成自定义的bean工厂,我只是为了演示才这样的啊,然后将保存到本地的代码加进去:

public  class MyBeanFactoryAwareGeneratorStrategy extends DefaultGeneratorStrategy {
   
     

		private final ClassLoader classLoader;

		public MyBeanFactoryAwareGeneratorStrategy(ClassLoader classLoader) {
   
     
			this.classLoader = classLoader;
		}

		@Override
		protected ClassGenerator transform(ClassGenerator cg) throws Exception {
   
     
			ClassEmitterTransformer transformer = new ClassEmitterTransformer() {
   
     
				@Override
				public void end_class() {
   
     
					declare_field(Constants.ACC_PUBLIC, "自定义的bean工厂", Type.getType(BeanFactory.class), null);
					super.end_class();
				}
			};
			return new TransformingClassGenerator(cg, transformer);
		}

		@Override
		public byte[] generate(ClassGenerator cg) throws Exception {
   
     
			if (this.classLoader == null) {
   
     
				return super.generate(cg);
			}

			Thread currentThread = Thread.currentThread();
			ClassLoader threadContextClassLoader;
			try {
   
     
				threadContextClassLoader = currentThread.getContextClassLoader();
			}
			catch (Throwable ex) {
   
     
				// Cannot access thread context ClassLoader - falling back...
				return super.generate(cg);
			}

			boolean overrideClassLoader = !this.classLoader.equals(threadContextClassLoader);
			if (overrideClassLoader) {
   
     
				currentThread.setContextClassLoader(this.classLoader);
			}
			try {
   
     
				//生成的字节码保存到本地
                byte[] generate = super.generate(cg);
                FileOutputStream fileOutputStream = null;
                try {
   
     
                    fileOutputStream = new FileOutputStream(new File("D:\\MyConfigProxy.class"));
                    try {
   
     
                        fileOutputStream.write(generate);
                    } catch (IOException e) {
   
     
                        e.printStackTrace();
                    } finally {
   
     
                        if (fileOutputStream != null) {
   
     
                            try {
   
     
                                fileOutputStream.flush();
                                fileOutputStream.close();
                            } catch (IOException e) {
   
     
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (FileNotFoundException e) {
   
     
                    e.printStackTrace();
                }

                return generate;
			}
			finally {
   
     
				if (overrideClassLoader) {
   
     
					// Reset original thread context ClassLoader.
					currentThread.setContextClassLoader(threadContextClassLoader);
				}
			}
		}
	}

被代理类

我们要增强的配置类:
*

结果:

可以看到前面的属性自定义的bean工厂被加进去了,CGLIB继承了目标类,实现了设置的接口。
*

增强的方法:

我们来看这段代码,首先会有个拦截器MethodInterceptor ,返回什么是要执行拦截器的方法的,如果拦截器不存在,才会去调用父类的userDao,我猜这里应该是为了单例来拦截,去查$$beanFactory里是否有实例,有就直接返回,没有才去创建,不然每次都调用会生成一个新的实例:

    final UserDao CGLIB$userDao$0() {
   
     
        return super.userDao();
    }

    public final UserDao userDao() {
   
     
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (var10000 == null) {
   
     
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        return var10000 != null ? (UserDao)var10000.intercept(this, CGLIB$userDao$0$Method, CGLIB$emptyArgs, CGLIB$userDao$0$Proxy) : super.userDao();
    }

EnhancedConfigurationsetBeanFactory方法也进行了拦截:
*
前面我们基本上把BeanFactoryPostProcessorBeanDefinitionRegistryPostProcessor的后置处理器处理方法讲完了,后面我们继续讲剩下的。

好了,今天就到这里了,希望对学习理解有帮助,大神看见勿喷,仅为自己的学习理解,能力有限,请多包涵。