2023-09-15
原文作者:王伟王胖胖 原文地址: https://blog.csdn.net/wangwei19871103/article/details/105770283

RefreshScope注解类实例化基本流程

202309152316235901.png

ScopedProxyFactoryBean的setBeanFactory

202309152316244992.png
下面就开始创建这个CGLIB动态代理对象,主要也就是scopedTargetSource设置了工厂,然后添加了DelegatingIntroductionInterceptor拦截器。

    	@Override
    	public void setBeanFactory(BeanFactory beanFactory) {
    		if (!(beanFactory instanceof ConfigurableBeanFactory)) {
    			throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory);
    		}
    		ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory;
    		//设置工厂,以便于后面获取代理对象
    		this.scopedTargetSource.setBeanFactory(beanFactory);
    
    		ProxyFactory pf = new ProxyFactory();
    		pf.copyFrom(this);
    		pf.setTargetSource(this.scopedTargetSource);
    
    		Assert.notNull(this.targetBeanName, "Property 'targetBeanName' is required");
    		Class<?> beanType = beanFactory.getType(this.targetBeanName);
    		if (beanType == null) {
    			throw new IllegalStateException("Cannot create scoped proxy for bean '" + this.targetBeanName +
    					"': Target type could not be determined at the time of proxy creation.");
    		}
    		if (!isProxyTargetClass() || beanType.isInterface() || Modifier.isPrivate(beanType.getModifiers())) {
    			pf.setInterfaces(ClassUtils.getAllInterfacesForClass(beanType, cbf.getBeanClassLoader()));
    		}
    		// 添加一个DelegatingIntroductionInterceptor拦截器
    		
    		ScopedObject scopedObject = new DefaultScopedObject(cbf, this.scopedTargetSource.getTargetBeanName());
    		pf.addAdvice(new DelegatingIntroductionInterceptor(scopedObject));
    
    		
    		pf.addInterface(AopInfrastructureBean.class);//标记接口
    
    		this.proxy = pf.getProxy(cbf.getBeanClassLoader());//创建cglib动态代理
    	}

202309152316250633.png

LockedScopedProxyFactoryBean的setBeanFactory

继续回到这里,动态代理对象创建完之后就可以获取了:

202309152316255944.png

202309152316262815.png
然后将自己也加入增强器里,放在第一个位置上,优先执行。

202309152316267836.png
增强后的:

202309152316275457.png
也就是说这个代理对象有两个拦截器,一个是LockedScopedProxyFactoryBean,一个是DelegatingIntroductionInterceptor,调用方法的时候会先通过他们,但是后面你会发现LockedScopedProxyFactoryBean拦截之后直接返回了,不会执行后面的拦截器了。

RefreshScope的eagerlyInitialize

上下文刷新完成的最后会进行ContextRefreshedEvent事件的通知。

202309152316281818.png
最后到eagerlyInitialize方法中,这里会遍历所有的bean名字,找出bean定义的scope=refresh的且非懒加载的,然后进行一次获取,就是提前实例化啦。

    	private void eagerlyInitialize() {
    		for (String name : this.context.getBeanDefinitionNames()) {
    			BeanDefinition definition = this.registry.getBeanDefinition(name);
    			if (this.getName().equals(definition.getScope())//范围名字是refresh
    					&& !definition.isLazyInit()) {
    				Object bean = this.context.getBean(name);
    				if (bean != null) {
    					bean.getClass();
    				}
    			}
    		}
    	}

实例化的操作可跟一般的不一样,我们下次说。

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

阅读全文