Spring容器的刷新过程

Posted 恒奇恒毅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring容器的刷新过程相关的知识,希望对你有一定的参考价值。

Spring容器的刷新过程是Spring框架非常稳定的12个大步骤,接口由ConfigurableApplicationContext定义,其核心实现在AbstractApplicationContext类中。

BeanFactory的创建及预准备工作

1、prepareRefresh()刷新前的预处理;

	protected void prepareRefresh() 
		this.startupDate = System.currentTimeMillis();
		this.closed.set(false);
		this.active.set(true);

		if (logger.isInfoEnabled()) 
			logger.info("Refreshing " + this);
		

		// Initialize any placeholder property sources in the context environment
		initPropertySources();

		// Validate that all properties marked as required are resolvable
		// see ConfigurablePropertyResolver#setRequiredProperties
		getEnvironment().validateRequiredProperties();

		// Allow for the collection of early ApplicationEvents,
		// to be published once the multicaster is available...
		this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
	
  1. initPropertySources()初始化一些属性设置;子类自定义个性化的属性设置方法;
  2. getEnvironment().validateRequiredProperties();检验属性的合法等
  3. earlyApplicationEvents= new LinkedHashSet();初始化保存容器中的一些早期的事件的容器;

2、obtainFreshBeanFactory();获取BeanFactory;

	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() 
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (logger.isDebugEnabled()) 
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		
		return beanFactory;
	
  1. refreshBeanFactory();刷新【创建】BeanFactory;在其子类 GenericApplicationContext 创建了一个this.beanFactory = new DefaultListableBeanFactory();设置id;
  2. getBeanFactory();返回刚才GenericApplicationContext创建的BeanFactory对象;
  3. 将创建的BeanFactory【DefaultListableBeanFactory】返回;
  4. 这里我们看到ApplicationContext与BeanFactory之间并不是直接继承的关系,而是使用了组合复用。

3、prepareBeanFactory(beanFactory);BeanFactory的预准备工作(BeanFactory进行一些设置);

	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) 
		// Tell the internal bean factory to use the context's class loader etc.
		beanFactory.setBeanClassLoader(getClassLoader());
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
		beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
		beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

		// BeanFactory interface not registered as resolvable type in a plain factory.
		// MessageSource registered (and found for autowiring) as a bean.
		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
		beanFactory.registerResolvableDependency(ApplicationContext.class, this);

		// Register early post-processor for detecting inner beans as ApplicationListeners.
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

		// Detect a LoadTimeWeaver and prepare for weaving, if found.
		if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) 
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			// Set a temporary ClassLoader for type matching.
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		

		// Register default environment beans.
		if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) 
			beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
		
		if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) 
			beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
		
		if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) 
			beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
		
	
  1. 设置BeanFactory的类加载器、表达式解析器…
  2. 添加部分BeanPostProcessor【ApplicationContextAwareProcessor
  3. 设置忽略的自动装配的接口EnvironmentAwareEmbeddedValueResolverAwareResourceLoaderAwareApplicationEventPublisherAwareMessageSourceAwareApplicationContextAware
  4. 注册可以解析的自动装配;我们能直接在任何组件中自动注入:
    BeanFactoryResourceLoaderApplicationEventPublisherApplicationContext
  5. 添加BeanPostProcessor【ApplicationListenerDetector】,这里貌似与PostProcessorRegistrationDelegate#registerBeanPostProcessors(ConfigurableListableBeanFactory, AbstractApplicationContext)重复了,但是由于addBeanPostProcessor是先删除再添加,所以无所谓。
  6. 添加编译时的AspectJ;
  7. 给BeanFactory中注册一些能用的组件;
    environment【ConfigurableEnvironment】、
    systemProperties【Map<String, Object>】、
    systemEnvironment【Map<String, Object>

4、postProcessBeanFactory(beanFactory);BeanFactory准备工作完成后进行的后置处理工作;

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

调用BeanFactoryPostProcessor

5、invokeBeanFactoryPostProcessors(beanFactory);执行BeanFactoryPostProcessor的方法;

BeanFactoryPostProcessorBeanFactory的后置处理器。在BeanFactory标准初始化之后执行的;
两个接口:BeanFactoryPostProcessorBeanDefinitionRegistryPostProcessor

  1. 先执行BeanFactoryPostProcessor的方法;
    先执行BeanDefinitionRegistryPostProcessor

     1.1.  获取所有的BeanDefinitionRegistryPostProcessor;
     
     1.2. 看先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor、
     	postProcessor.postProcessBeanDefinitionRegistry(registry)
     	
     1.3. 在执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor;
     	postProcessor.postProcessBeanDefinitionRegistry(registry)
     	
     1.4. 最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors;
     	postProcessor.postProcessBeanDefinitionRegistry(registry)
    
  2. 再执行BeanFactoryPostProcessor的方法

     2.1. 获取所有的BeanFactoryPostProcessor
     2.2. 看先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor、
     	postProcessor.postProcessBeanFactory()
     2.3. 在执行实现了Ordered顺序接口的BeanFactoryPostProcessor;
     	postProcessor.postProcessBeanFactory()
     2.4. 最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor;
     	postProcessor.postProcessBeanFactory()
    

    具体详细的剖析参见BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor机制

注册BeanPostProcessor

6、registerBeanPostProcessors(beanFactory);注册BeanPostProcessor(Bean的后置处理器)【 intercept bean creation】

不同接口类型的BeanPostProcessor;在Bean创建前后的执行时机是不一样的
BeanPostProcessor、
InstantiationAwareBeanPostProcessor、
SmartInstantiationAwareBeanPostProcessor、
DestructionAwareBeanPostProcessor、
MergedBeanDefinitionPostProcessor、

  1. 获取所有的 BeanPostProcessor;后置处理器都默认可以通过PriorityOrdered、Ordered接口来执行优先级
  2. 先注册PriorityOrdered优先级接口的BeanPostProcessor;
    把每一个BeanPostProcessor;添加到BeanFactory中
    beanFactory.addBeanPostProcessor(postProcessor);
  3. 再注册Ordered接口的
  4. 最后注册没有实现任何优先级接口的
  5. 最终注册MergedBeanDefinitionPostProcessor;
  6. 注册一个ApplicationListenerDetector;来在Bean创建完成后检查是否是ApplicationListener,如果是applicationContext.addApplicationListener((ApplicationListener<?>) bean);
    具体详细的剖析参见BeanPostProcessor机制

初始化MessageSource

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

	protected void initMessageSource() 
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) 
			this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
			// Make MessageSource aware of parent MessageSource.
			if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) 
				HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
				if (hms.getParentMessageSource() == null) 
					// Only set parent context as parent MessageSource if no parent MessageSource
					// registered already.
					hms.setParentMessageSource(getInternalParentMessageSource());
				
			
			if (logger.isDebugEnabled()) 
				logger.debug("Using MessageSource [" + this.messageSource + "]");
			
		
		else 
			// Use empty MessageSource to be able to accept getMessage calls.
			DelegatingMessageSource dms = new DelegatingMessageSource();
			dms.setParentMessageSource(getInternalParentMessageSource());
			this.messageSource = dms;
			beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
			if (logger.isDebugEnabled()) 
				logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
						"': using default [" + this.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);

初始化事件派发器

8、initApplicationEventMulticaster();初始化事件派发器;

	protected void initApplicationEventMulticaster() 
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) 
			this.applicationEventMulticaster =
					beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
			if (logger.isDebugEnabled()) 
				logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
			
		
		else 
			this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
			beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
			if (logger.isDebugEnabled()) 
				logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
						APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
						"': using default [" + this.applicationEventMulticaster + "]");
			
		
	
  1. 获取BeanFactory
  2. 从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster;
  3. 如果上一步没有配置;创建一个SimpleApplicationEventMulticaster
  4. 将创建的ApplicationEventMulticaster添加到BeanFactory中,以后其他组件直接自动注入

onRefresh

9、onRefresh();留给子容器(子类)

  1. 子类重写这个方法,在容器刷新的时候可以自定义逻辑;模板方法模式的体现

注册ApplicationListener

10、registerListeners();给容器中将所有的ApplicationListener注册进来;

	protected void registerListeners() 
		// Register statically specified listeners first.
		for (ApplicationListener<?> listener : getApplicationListeners()) 
			getApplicationEventMulticaster().addApplicationListener(listener);
		

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let post-processors apply to them!
		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
		for (String listenerBeanName : listenerBeanNames) 
			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
		

		// Publish early application events now that we finally have a multicaster...
		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
		this.earlyApplicationEvents = null;
		if (earlyEventsToProcess != null) 
			for (ApplicationEvent earlyEvent : earlyEventsToProcess) 
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			
		
	
  1. 从容器中拿到所有的ApplicationListener
  2. 将每个监听器添加到事件派发器中;
    getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  3. 派发之前步骤产生的事件;

初始化剩余的Singleton

11、finishBeanFactoryInitialization(beanFactory);初始化所有剩下的单实例bean;

	protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) 
		// Initialize conversion service for this context.
		if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) 
			beanFactory.setConversionService(
					beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
		

		// Register a default embedded value resolver if no bean post-processor
		// (such as a PropertyPlaceholderConfigurer bean) registered any before:
		// at this point, primarily for resolution in annotation attribute values.
		if (!beanFactory.hasEmbeddedValueResolver()) 
			beanFactory.addEmbeddedValueResolver(new StringValueResolver() 
				@Override
				public String resolveStringValue(String strVal) 
					return getEnvironment().resolvePlaceholders(strVal);
				
			);
		

		// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
		for (String weaverAwareName : weaverAwareNames) 
			getBean(weaverAwareName);
		

		// Stop using the temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(null);

		// Allow for caching all bean definition metadata, not expecting further changes.
		beanFactory.freezeConfiguration();

		// Instantiate all remaining (non-lazy-init) singletons.
		beanFactory.preInstantiateSingletons();
	
beanFactory.preInstantiateSingletons();初始化后剩下的单实例bean
		1)、获取容器中的所有Bean,依次进行初始化和创建对象
		2)、获取Bean的定义信息;RootBeanDefinition
		3)、Bean不是抽象的,是单实例的,不是懒加载;
			1)、判断是否是FactoryBean;是否是实现FactoryBean接口的Bean2)、不是工厂Bean。利用getBean(beanName);创建对象
				0getBean(beanName); ioc.getBean();
				1doGetBean(name, null, null, false);
				2、先获取缓存中保存的单实例Bean。如果能获取到说明这个Bean之前被创建过(所有创建过的单实例Bean都会被缓存起来)
					从private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);获取的
				3、缓存中获取不到,开始Bean的创建对象流程;
				4、标记当前bean已经被创建
				5、获取Bean的定义信息;
				6、【获取当前Bean依赖的其他Bean;如果有按照getBean()把依赖的Bean先创建出来;】
				7、启动单实例Bean的创建流程;
					1)、createBean(beanName, mbd, args);
					2)、Object bean = resolveBeforeInstantiation(beanName, mbdToUse);BeanPostProcessor先拦截返回代理对象;
						【InstantiationAwareBeanPostProcessor】:提前执行;
						先触发:postProcessBeforeInstantiation();
						如果有返回值:触发postProcessAfterInitialization()3)、如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象;调用44)、Object beanInstance = doCreateBean(beanName, mbdToUse, args);创建Bean
						 1)、【创建Bean实例】;createBeanInstance(beanName, mbd, args);
						 	利用工厂方法或者对象的构造器创建出Bean实例;
						 2)、applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
						 	调用MergedBeanDefinitionPostProcessorpostProcessMergedBeanDefinition(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);执行xxxAware接口的方法
						 		BeanNameAwareBeanClassLoaderAwareBeanFactoryAware
						 	2)、【执行后置处理器初始化之前】applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
						 		BeanPostProcessor.postProcessBeforeInitialization();
						 	3)、【执行初始化方法】invokeInitMethods(beanName, wrappedBean, mbd);
						 		1)、是否是InitializingBean接口的实现;执行接口规定的初始化;
						 		2)、是否自定义初始化方法;
						 	4)、【执行后置处理器初始化之后】applyBeanPostProcessorsAfterInitialization
						 		BeanPostProcessor.postProcessAfterInitialization()5)、注册Bean的销毁方法;
					5)、将创建的Bean添加到缓存中singletonObjects;
		所有Bean都利用getBean创建完成以后;
			检查所有的Bean是否是SmartInitializingSingleton接口的;如果是;就执行afterSingletonsInstantiated()

完成刷新

12、finishRefresh();完成BeanFactory的初始化创建工作;IOC容器就创建完成;

	protected void finishRefresh() 
		// Initialize lifecycle processor for this context.
		initLifecycleProcessor();

		// Propagate refresh to lifecycle processor first.
		getLifecycleProcessor().onRefresh();

		// Publish the final event.
		publishEvent(new ContextRefreshedEvent(this));

		// Participate in LiveBeansView MBean, if active.
		Spring源码01---容器刷新前配置

Spring IOC源码分析之-刷新前的准备工作

SpringBean管理

03.Spring IoC 容器 - 初始化

Mybatis在spring容器中的初始化过程

spring5 源码深度解析-----ApplicationContext容器refresh过程