Spring的容器创建过程

Spring容器的refresh()【创建刷新】


一、prepareRefresh()刷新前的预处理

1、initPropertySources()初始化一些属性设置;子类自定义个性化的属性设置方法;

2、getEnvironment().validateRequiredProperties();检验属性的合法等

3、earlyApplicationEvents= new LinkedHashSet<ApplicationEvent>();保存容器中的一些早期的事件;


二、obtainFreshBeanFactory():创建BeanFactory对象,并解析xml封装成BeanDefinition对象

1、refreshBeanFactory();刷新【创建】BeanFactory;
		创建了一个this.beanFactory = new DefaultListableBeanFactory();
		设置id;
2、getBeanFactory();返回刚才GenericApplicationContext创建的BeanFactory对象;

3、将创建的BeanFactory【DefaultListableBeanFactory】返回;


三、prepareBeanFactory(beanFactory):BeanFactory的预准备工作(BeanFactory进行一些设置属性)

1、设置BeanFactory的类加载器、支持表达式解析器...

2、添加部分BeanPostProcessor【ApplicationContextAwareProcessor】

3、设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx;

4、注册可以解析的自动装配;我们能直接在任何组件中自动注入:
		BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext

5、添加BeanPostProcessor【ApplicationListenerDetector】

6、添加编译时的AspectJ;

7、给BeanFactory中注册一些能用的组件;
	environment【ConfigurableEnvironment】、
	systemProperties【Map<String, Object>】、
	systemEnvironment【Map<String, Object>】


四、postProcessBeanFactory(beanFactory):BeanFactory准备工作完成后,创建BeanFactory的处理器

1、子类通过重写这个方法来在BeanFactory创建并预准备完成以后做进一步的设置

---------------以上是BeanFactory的创建及预准备工作-----------------------------------------------


五、invokeBeanFactoryPostProcessors(beanFactory):【执行BeanFactory的后置处理器】


第一部分:处理 BeanDefinitionRegistryPostProcessor

if (beanFactory instanceof BeanDefinitionRegistry) {
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    
    // 分类存储处理器
    List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<>();
    List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<>();
    
    // 1. 首先处理手动注册的BeanFactoryPostProcessor
    for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
        if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
            BeanDefinitionRegistryPostProcessor registryProcessor =
                    (BeanDefinitionRegistryPostProcessor) postProcessor;

            // 解析@ComponentScan扫描对应包下的@Component、@Configuration、@Repository、@Service、@Controller等注解的类,生成扫描到的类的Bean定义信息并添加到容器中
            registryProcessor.postProcessBeanDefinitionRegistry(registry);
            registryProcessors.add(registryProcessor);
        }
        else {
            regularPostProcessors.add(postProcessor);
        }
    }
    
    // 2. 处理容器中注册的BeanDefinitionRegistryPostProcessor
    List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
    
    // 2.1 首先处理实现了PriorityOrdered的处理器
    String[] postProcessorNames = beanFactory.getBeanNamesForType(...);
    for (String ppName : postProcessorNames) {
        if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            currentRegistryProcessors.add(beanFactory.getBean(...));
            processedBeans.add(ppName);
        }
    }
    sortPostProcessors(currentRegistryProcessors, beanFactory); // 排序
    registryProcessors.addAll(currentRegistryProcessors);
    invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
    currentRegistryProcessors.clear();
    
    // 2.2 然后处理实现了Ordered的处理器
    // (类似PriorityOrdered的处理逻辑)
    
    // 2.3 最后处理普通处理器
    boolean reiterate = true;
    while (reiterate) {
        reiterate = false;
        postProcessorNames = beanFactory.getBeanNamesForType(...);
        for (String ppName : postProcessorNames) {
            if (!processedBeans.contains(ppName)) {
                currentRegistryProcessors.add(beanFactory.getBean(...));
                processedBeans.add(ppName);
                reiterate = true; // 可能有新注册的处理器
            }
        }
        // 排序并执行...
    }
    
    // 3. 执行所有处理器的postProcessBeanFactory方法
    invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}


第二部分:处理常规 BeanFactoryPostProcessor

// 1. 获取所有BeanFactoryPostProcessor
String[] postProcessorNames = 
        beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

// 2. 按优先级分类
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();

for (String ppName : postProcessorNames) {
    if (processedBeans.contains(ppName)) {
        continue; // 已经处理过
    }
    else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
        priorityOrderedPostProcessors.add(beanFactory.getBean(...));
    }
    else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
        orderedPostProcessorNames.add(ppName);
    }
    else {
        nonOrderedPostProcessorNames.add(ppName);
    }
}

// 3. 按顺序执行
// 3.1 执行PriorityOrdered
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

// 3.2 执行Ordered
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
    orderedPostProcessors.add(beanFactory.getBean(...));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

// 3.3 执行普通处理器
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
    nonOrderedPostProcessors.add(beanFactory.getBean(...));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

// 4. 清除缓存
beanFactory.clearMetadataCache();


六、registerBeanPostProcessors(beanFactory):创建并注册BeanPostProcessor(Bean的处理器)【 intercept bean creation】

注释:BeanPostProcessor(Bean的处理器)有两个方法,postProcessBeforeInitialization(Bean处理器的前置方法)和 postProcessAfterInitialization(Bean处理器的后置方法)

 不同接口类型的BeanPostProcessor;在Bean创建前后的执行时机是不一样的
		BeanPostProcessor、
		DestructionAwareBeanPostProcessor、
		InstantiationAwareBeanPostProcessor、
		SmartInstantiationAwareBeanPostProcessor、
		MergedBeanDefinitionPostProcessor【internalPostProcessors】、
		
		1)、获取所有的 BeanPostProcessor;后置处理器都默认可以通过PriorityOrdered、Ordered接口来执行优先级
		2)、先注册PriorityOrdered优先级接口的BeanPostProcessor;
              a、创建bean后置处理器 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			  b、把每一个BeanPostProcessor;添加到BeanFactory中
			        beanFactory.addBeanPostProcessor(postProcessor);
		3)、再注册Ordered接口的
		4)、最后注册没有实现任何优先级接口的
		5)、最终注册MergedBeanDefinitionPostProcessor;
		6)、注册一个ApplicationListenerDetector;来在Bean创建完成后检查是否是ApplicationListener,如果是
			 applicationContext.addApplicationListener((ApplicationListener<?>) bean);  


七、initMessageSource():初始化MessageSource组件(做国际化功能;消息绑定,消息解析)

	1)、获取BeanFactory
	2)、看容器中是否有id为messageSource的,类型是MessageSource的组件
		如果有赋值给messageSource,如果没有自己创建一个DelegatingMessageSource;
			MessageSource:取出国际化配置文件中的某个key的值;能按照区域信息获取;
	3)、把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource;
		beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);	
		MessageSource.getMessage(String code, Object[] args, String defaultMessage, Locale locale);


八、initApplicationEventMulticaster():初始化事件派发器

  	1)、获取BeanFactory
	2)、从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster;
	3)、如果上一步没有配置;创建一个SimpleApplicationEventMulticaster
	4)、将创建的ApplicationEventMulticaster添加到BeanFactory中,以后其他组件直接自动注入


九、onRefresh():留给子容器(子类)

    1)、子类重写这个方法,在容器刷新的时候可以自定义逻辑;


十、registerListeners():注册监听器

    1)、从容器中拿到所有的ApplicationListener
	2)、将每个监听器添加到事件派发器中;
		    getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
	3)、派发之前步骤产生的事件;


十一、finishBeanFactoryInitialization(beanFactory):初始化所有剩下的单实例bean

beanFactory.preInstantiateSingletons();初始化后剩下的单实例bean
	1)、获取容器中的所有Bean,依次进行初始化和创建对象
	2)、获取Bean的定义信息;RootBeanDefinition
	3)、Bean不是抽象的,是单实例的,是懒加载;
			1)、判断是否是FactoryBean;是否是实现FactoryBean接口的Bean;
			2)、不是工厂Bean。利用getBean(beanName);创建对象
					0、getBean(beanName);DefaultListableBeanFactory#preInstantiateSingletons-->getBean(beanName);
					1、doGetBean(name, null, null, false);
					2、先获取缓存中保存的单实例Bean。如果能获取到说明这个Bean之前被创建过(所有创建过的单实例Bean都会被缓存起来)
							Object sharedInstance = getSingleton(beanName);
							从private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);获取的

					3、缓存中获取不到,开始Bean的创建对象流程;
					4、标记当前bean已经被创建, 防止其他线程重新创建 Bean;markBeanAsCreated(beanName);
					5、获取Bean的定义信息;final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
					6、【获取当前Bean依赖的其他Bean;如果有按照getBean(dep),优先把依赖的Bean先创建出来】
					7、启动单实例Bean的创建流程;
							    1)、createBean(beanName, mbd, args);
    										sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                                                // 相当于创建了一个ObjectFactory类型的匿名内部类,去实现ObjectFactory接口中的getObject()方法
    											@Override
    											public Object getObject() throws BeansException {
    												try {
                                                        // 真正的Bean对象创建过程
    													return createBean(beanName, mbd, args);
    												}
    												catch (BeansException ex) {
    													// Explicitly remove instance from singleton cache: It might have been put there
    													// eagerly by the creation process, to allow for circular reference resolution.
    													// Also remove any beans that received a temporary reference to the bean.
    													destroySingleton(beanName);
    													throw ex;
    												}
    											}
    										});

                                            等效于以下代码

                                            ObjectFactory objectFactory = new ObjectFactory() {
		                                            @Override
                                        			public Object getObject() throws BeansException {
                                        				try {
                                        					return createBean(beanName, mbd, args);//创建代理对象,也可能是非代理
                                        				}
                                        				catch (BeansException ex) {
                                        					// Explicitly remove instance from singleton cache: It might have been put there
                                        					// eagerly by the creation process, to allow for circular reference resolution.
                                        					// Also remove any beans that received a temporary reference to the bean.
                                        					destroySingleton(beanName);
                                        					throw ex;
                                        				}
                                        			}
                                        		};

                                           sharedInstance = getSingleton(beanName, objectFactory);

                                           执行顺序为:getSingleton(beanName, objectFactory)---> singletonFactory.getObject() ----> createBean(beanName, mbd, args)


    							2)、Object bean = resolveBeforeInstantiation(beanName, mbdToUse);让BeanPostProcessor处理器先拦截bean返回proxy代理对象;
    									【InstantiationAwareBeanPostProcessor】:提前执行;
    									 先触发:postProcessBeforeInstantiation();
    									 如果有返回值:触发postProcessAfterInitialization()
    							3)、如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象;调用4)
    							4)、Object beanInstance = doCreateBean(beanName, mbdToUse, args);创建Bean
    									    1)、【创建Bean实例】;createBeanInstance(beanName, mbd, args);
        											 利用工厂方法或者对象的构造器创建出Bean实例;
        									2)、applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);允许后置处理器修改bean的定义信息
        											 调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName);
        									3)、【Bean属性赋值】populateBean(beanName, mbd, instanceWrapper);
        												 ========= 赋值之前 =================================
        													1)、拿到InstantiationAwareBeanPostProcessor后置处理器;
        														   postProcessAfterInstantiation();
        													2)、拿到InstantiationAwareBeanPostProcessor后置处理器;
        														   postProcessPropertyValues();
        												 ========= 赋值之前 =================================
        												 ========= 赋值 ====================================
        													3)、应用Bean属性的值;为属性利用setter方法等进行赋值;
        														   applyPropertyValues(beanName, mbd, bw, pvs);

        									4)、【Bean初始化】initializeBean(beanName, exposedObject, mbd);
        												1)、【执行Aware接口方法】invokeAwareMethods(beanName, bean); 校验该bean是否实现xxxAware接口(BeanNameAware、BeanClassLoaderAware、BeanFactoryAware等接口)对bean填充BeanName、BeanClassLoader、BeanFactory
        															
        												2)、【初始化之前执行后置处理器的前置方法】applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        															BeanPostProcessor.postProcessBeforeInitialization(); 是否生成bean的proxy代理对象返回
        												3)、【执行初始化方法】invokeInitMethods(beanName, wrappedBean, mbd);	
        															1)、是否是InitializingBean接口的实现;执行接口规定的初始化;
        															2)、是否自定义初始化方法;
        												4)、【初始化之后执行后置处理器的后置方法】applyBeanPostProcessorsAfterInitialization,
        															BeanPostProcessor.postProcessAfterInitialization();是否生成bean的proxy代理对象返回
        									5)、将已初始化完成的bean,注册到销毁disposableBeans容器中;registerDisposableBeanIfNecessary(beanName, bean, mbd);	但并没有真正销毁;this.disposableBeans.put(beanName, bean),key为beanName ===== value为 disposableBeanAdapter【bean的销毁适配器】
    												
    							5)、将创建的完整的Bean实例添加到singletonObjects一缓存中并删除二、三级缓存;
    									  第1)步执行完return createBean(beanName, mbd, args)后,
    									  重新回到DefaultSingletonBeanRegistry#getSingleton(String beanName, ObjectFactory<?> singletonFactory)方法
    									  -->singletonObject = singletonFactory.getObject()-->return createBean(beanName, mbd, args)继续往下执行addSingleton(beanName, singletonObject)【将Bean添加到singletonObjects【一级缓存】,并删除earlySingletonObjects【二级缓存】和 singletonFactories【三级缓存】】
						                      
						
				ioc容器就是这些Map;很多的Map里面保存了单实例Bean,环境信息.......;
				所有Bean都利用getBean创建完成以后;
				检查所有的Bean是否是SmartInitializingSingleton接口的;如果是;就执行afterSingletonsInstantiated();					


十二、finishRefresh();完成刷新过程,通知声明周期处理器LifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人

    1)、initLifecycleProcessor();初始化和生命周期有关的后置处理器;LifecycleProcessor
		    默认从容器中找是否有lifecycleProcessor的组件【LifecycleProcessor】;如果没有new DefaultLifecycleProcessor();
			加入到容器;
			
			写一个LifecycleProcessor的实现类,可以在BeanFactory
				void onRefresh();
				void onClose();	
	2)、getLifecycleProcessor().onRefresh();
		  拿到前面定义的生命周期处理器(BeanFactory);回调onRefresh();

	3)、publishEvent(new ContextRefreshedEvent(this));发布容器刷新完成事件;

	4)、liveBeansView.registerApplicationContext(this);


-----------------总结-----------------------------------------------------------

	1)、Spring容器在启动的时候,先会保存所有注册进来的Bean的定义信息;
		    1)、xml注册bean;<bean>
    		2)、注解注册Bean;@Service、@Component、@Bean、xxx

	2)、Spring容器会合适的时机创建这些Bean
		    1)、用到这个bean的时候;利用getBean创建bean;创建好以后保存在容器中;
    		2)、统一创建剩下所有的bean的时候;finishBeanFactoryInitialization();

	3)、后置处理器;BeanPostProcessor
	    	1)、每一个bean创建完成,都会使用各种后置处理器进行处理;来增强bean的功能;
    			AutowiredAnnotationBeanPostProcessor:处理自动注入
    			AnnotationAwareAspectJAutoProxyCreator:来做AOP功能;
    			xxx....
    			增强的功能注解:
    			AsyncAnnotationBeanPostProcessor
    			....
	4)、事件驱动模型;
    		ApplicationListener;事件监听;
    		ApplicationEventMulticaster;事件派发:


-----------------注意这段代码一与代码二是等效的-----------------------------------------------------------


代码一、

sharedInstance = getSingleton(beanName, () -> {
					try {
						return createBean(beanName, mbd, args);
					}
					catch (BeansException ex) {
						// Explicitly remove instance from singleton cache: It might have been put there
						// eagerly by the creation process, to allow for circular reference resolution.
						// Also remove any beans that received a temporary reference to the bean.
						destroySingleton(beanName);
						throw ex;
					}
				});


代码二、

  sharedInstance = getSingleton(beanName, () -> {
  			     @verride
  				 public object getObject throws BeansException{
  					try {
  						return createBean(beanName, mbd, args);
  					}catch (BeansException ex) {
  						// Explicitly remove instance from singleton cache: It might have been put there
  						// eagerly by the creation process, to allow for circular reference resolution.
  						// Also remove any beans that received a temporary reference to the bean.
  						destroySingleton(beanName);
  						throw ex;
  					}
  				 }
  				})
posted @ 2024-08-25 21:07  jock_javaEE  阅读(31)  评论(0)    收藏  举报