@Overridepublicvoidrefresh()throwsBeansException,IllegalStateException{synchronized(this.startupShutdownMonitor){// Prepare this context for refreshing.// 说明:准备工作,设置启动时间和标志,并初始化一些属性prepareRefresh();// Tell the subclass to refresh the internal bean factory.// 说明:创建BeanFactory,并从配置文件或注解中加载BeanDefinitions信息ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();// Prepare the bean factory for use in this context.// 说明:准备BeanFactory,设置类加载器,注册几个BeanPostProcessors,忽略几个接口类型的自动装配,设置几个主bean,注册几个系统环境相关的beanprepareBeanFactory(beanFactory);try{// Allows post-processing of the bean factory in context subclasses.// 说明:模板方法,子类实现postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.// 说明:执行BeanFactory后处理器invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.// 说明:注册Bean后处理器registerBeanPostProcessors(beanFactory);// Initialize message source for this context.// 说明:国际化相关 beanName=messageSourceinitMessageSource();// Initialize event multicaster for this context.// 说明:初始化事件广播器initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses.// 说明:模板方法子类重写,比如springboot的初始化tomcat服务器就在此覆盖重写onRefresh();// Check for listener beans and register them.// 说明:注册监听器,将将ApplicationListener对象和bean注册到上面的事件广播器,然后发布早期事件earlyApplicationEvents// 这里用到观察者模式,也可以叫发布订阅模式registerListeners();// Instantiate all remaining (non-lazy-init) singletons.// 说明:重点的非懒加载bean的实例化和初始化部分finishBeanFactoryInitialization(beanFactory);// Last step: publish corresponding event.finishRefresh();}catch(BeansException ex){if(logger.isWarnEnabled()){
logger.warn("Exception encountered during context initialization - "+"cancelling refresh attempt: "+ ex);}// Destroy already created singletons to avoid dangling resources.destroyBeans();// Reset 'active' flag.cancelRefresh(ex);// Propagate exception to caller.throw ex;}finally{// Reset common introspection caches in Spring's core, since we// might not ever need metadata for singleton beans anymore...resetCommonCaches();}}}
prepareRefresh()
/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/protectedvoidprepareRefresh(){// Switch to active.this.startupDate =System.currentTimeMillis();this.closed.set(false);this.active.set(true);if(logger.isDebugEnabled()){if(logger.isTraceEnabled()){
logger.trace("Refreshing "+this);}else{
logger.debug("Refreshing "+getDisplayName());}}// Initialize any placeholder property sources in the context environment.// 说明:模板方法子类实现,可以自己设置一些属性到容器中initPropertySources();// Validate that all properties marked as required are resolvable:// see ConfigurablePropertyResolver#setRequiredPropertiesgetEnvironment().validateRequiredProperties();// Store pre-refresh ApplicationListeners...if(this.earlyApplicationListeners ==null){this.earlyApplicationListeners =newLinkedHashSet<>(this.applicationListeners);}else{// Reset local application listeners to pre-refresh state.this.applicationListeners.clear();this.applicationListeners.addAll(this.earlyApplicationListeners);}// Allow for the collection of early ApplicationEvents,// to be published once the multicaster is available...this.earlyApplicationEvents =newLinkedHashSet<>();}
obtainFreshBeanFactory()->refreshBeanFactory()
/**
* This implementation performs an actual refresh of this context's underlying
* bean factory, shutting down the previous bean factory (if any) and
* initializing a fresh bean factory for the next phase of the context's lifecycle.
*/@OverrideprotectedfinalvoidrefreshBeanFactory()throwsBeansException{// 销毁之前的BeanFactoryif(hasBeanFactory()){destroyBeans();closeBeanFactory();}try{// 说明:创建新的DefaultListableBeanFactory beanFactory =createBeanFactory();// 说明:设置序列号ID
beanFactory.setSerializationId(getId());// 说明:定制 如allowBeanDefinitionOverriding,allowCircularReferencescustomizeBeanFactory(beanFactory);// 说明:加载bean定义信息,这里使用了策略模式,不同的读取器读取不同的配置文件(xml,属性配置文件等),接口为BeanDefinitionReader,这里使用XmlBeanDefinitionReader的实现类读取loadBeanDefinitions(beanFactory);// 此时beanFactory 就有了bean的定义信息this.beanFactory = beanFactory;}catch(IOException ex){thrownewApplicationContextException("I/O error parsing bean definition source for "+getDisplayName(), ex);}}
loadBeanDefinitions()
/**
* Loads the bean definitions via an XmlBeanDefinitionReader.
* @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
* @see #initBeanDefinitionReader
* @see #loadBeanDefinitions
*/@OverrideprotectedvoidloadBeanDefinitions(DefaultListableBeanFactory beanFactory)throwsBeansException,IOException{// Create a new XmlBeanDefinitionReader for the given BeanFactory.XmlBeanDefinitionReader beanDefinitionReader =newXmlBeanDefinitionReader(beanFactory);// Configure the bean definition reader with this context's// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(newResourceEntityResolver(this));// Allow a subclass to provide custom initialization of the reader,// then proceed with actually loading the bean definitions.initBeanDefinitionReader(beanDefinitionReader);loadBeanDefinitions(beanDefinitionReader);}
prepareBeanFactory()
/**
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/protectedvoidprepareBeanFactory(ConfigurableListableBeanFactory beanFactory){// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(newStandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(newResourceEditorRegistrar(this,getEnvironment()));// Configure the bean factory with context callbacks.// 说明:这个后处理器会在bean初始化前调用postProcessBeforeInitialization,将实现各种xxxAware的bean自动装配上对应的xxx属性,如实现ApplicationContextAware则会调用setApplicationContext方法设置
beanFactory.addBeanPostProcessor(newApplicationContextAwareProcessor(this));// 说明:因为注册了上面后处理器,所以相关接口的bean设置为不进行自动装配 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.// 说明:通过byType自动装配时,如果容器中有多个该类型的实例,调用registerResolvableDependency可以指定一个bean作为注入对象,与@Primary注解功能很相似// 说明:另外还可以通过实现BeanFactoryPostProcessor重写postProcessBeanFactory方法类指定自己的主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(newApplicationListenerDetector(this));// Detect a LoadTimeWeaver and prepare for weaving, if found.// 说明:和aop相关的AspectJif(beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)){
beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory));// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));}// Register default environment beans.// 说明:手动注册一些beanif(!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());}}
postProcessBeanFactory()
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for registering special
* BeanPostProcessors etc in certain ApplicationContext implementations.
* @param beanFactory the bean factory used by the application context
*/protectedvoidpostProcessBeanFactory(ConfigurableListableBeanFactory beanFactory){// 说明:重写可以再注册一些自己的BeanPostProcessors 或 干一些其他事情}
invokeBeanFactoryPostProcessors()
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before singleton instantiation.
*/protectedvoidinvokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory){// 说明:使用委托类来执行BeanFactory的后处理器PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory,getBeanFactoryPostProcessors());// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)// 说明:又是aop相关的织入if(beanFactory.getTempClassLoader()==null&& beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)){
beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));}}
// 说明:先执行BeanDefinitionRegistryPostProcessors 后处理器,该处理器本身也实现了BeanFactoryPostProcessors 接口 ,所以先执行调用BeanDefinitionRegistryPostProcessors.postProcessBeanDefinitionRegistry(),在执行调用BeanFactoryPostProcessors.postProcessBeanFactory(),还需要通过优先排序,排序,其他未排序的顺序来执行// 后面再执行只实现BeanFactoryPostProcessors接口的后处理器,也是按照优先排序,排序,其他未排序的顺序来执行publicstaticvoidinvokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory,List<BeanFactoryPostProcessor> beanFactoryPostProcessors){// Invoke BeanDefinitionRegistryPostProcessors first, if any.Set<String> processedBeans =newHashSet<>();if(beanFactory instanceofBeanDefinitionRegistry){BeanDefinitionRegistry registry =(BeanDefinitionRegistry) beanFactory;List<BeanFactoryPostProcessor> regularPostProcessors =newArrayList<>();List<BeanDefinitionRegistryPostProcessor> registryProcessors =newArrayList<>();for(BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors){if(postProcessor instanceofBeanDefinitionRegistryPostProcessor){BeanDefinitionRegistryPostProcessor registryProcessor =(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);}else{
regularPostProcessors.add(postProcessor);}}// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let the bean factory post-processors apply to them!// Separate between BeanDefinitionRegistryPostProcessors that implement// PriorityOrdered, Ordered, and the rest.List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors =newArrayList<>();// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class,true,false);for(String ppName : postProcessorNames){if(beanFactory.isTypeMatch(ppName,PriorityOrdered.class)){
currentRegistryProcessors.add(beanFactory.getBean(ppName,BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class,true,false);for(String ppName : postProcessorNames){if(!processedBeans.contains(ppName)&& beanFactory.isTypeMatch(ppName,Ordered.class)){
currentRegistryProcessors.add(beanFactory.getBean(ppName,BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.boolean reiterate =true;while(reiterate){
reiterate =false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class,true,false);for(String ppName : postProcessorNames){if(!processedBeans.contains(ppName)){
currentRegistryProcessors.add(beanFactory.getBean(ppName,BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate =true;}}sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();}// Now, invoke the postProcessBeanFactory callback of all processors handled so far.invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);}else{// Invoke factory processors registered with the context instance.invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);}// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let the bean factory post-processors apply to them!String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class,true,false);// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,// Ordered, and the rest.List<BeanFactoryPostProcessor> priorityOrderedPostProcessors =newArrayList<>();List<String> orderedPostProcessorNames =newArrayList<>();List<String> nonOrderedPostProcessorNames =newArrayList<>();for(String ppName : postProcessorNames){if(processedBeans.contains(ppName)){// skip - already processed in first phase above}elseif(beanFactory.isTypeMatch(ppName,PriorityOrdered.class)){
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName,BeanFactoryPostProcessor.class));}elseif(beanFactory.isTypeMatch(ppName,Ordered.class)){
orderedPostProcessorNames.add(ppName);}else{
nonOrderedPostProcessorNames.add(ppName);}}// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.sortPostProcessors(priorityOrderedPostProcessors, beanFactory);invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);// Next, invoke the BeanFactoryPostProcessors that implement Ordered.List<BeanFactoryPostProcessor> orderedPostProcessors =newArrayList<>(orderedPostProcessorNames.size());for(String postProcessorName : orderedPostProcessorNames){
orderedPostProcessors.add(beanFactory.getBean(postProcessorName,BeanFactoryPostProcessor.class));}sortPostProcessors(orderedPostProcessors, beanFactory);invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);// Finally, invoke all other BeanFactoryPostProcessors.List<BeanFactoryPostProcessor> nonOrderedPostProcessors =newArrayList<>(nonOrderedPostProcessorNames.size());for(String postProcessorName : nonOrderedPostProcessorNames){
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName,BeanFactoryPostProcessor.class));}invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);// Clear cached merged bean definitions since the post-processors might have// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();}
注册bean后处理器-registerBeanPostProcessors()
/**
* Instantiate and register all BeanPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before any instantiation of application beans.
*/protectedvoidregisterBeanPostProcessors(ConfigurableListableBeanFactory beanFactory){PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory,this);}
// 说明:注册bean后处理器publicstaticvoidregisterBeanPostProcessors(ConfigurableListableBeanFactory beanFactory,AbstractApplicationContext applicationContext){String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class,true,false);// Register BeanPostProcessorChecker that logs an info message when// a bean is created during BeanPostProcessor instantiation, i.e. when// a bean is not eligible for getting processed by all BeanPostProcessors.int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount()+1+ postProcessorNames.length;
beanFactory.addBeanPostProcessor(newBeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));// Separate between BeanPostProcessors that implement PriorityOrdered,// Ordered, and the rest.List<BeanPostProcessor> priorityOrderedPostProcessors =newArrayList<>();List<BeanPostProcessor> internalPostProcessors =newArrayList<>();List<String> orderedPostProcessorNames =newArrayList<>();List<String> nonOrderedPostProcessorNames =newArrayList<>();for(String ppName : postProcessorNames){if(beanFactory.isTypeMatch(ppName,PriorityOrdered.class)){BeanPostProcessor pp = beanFactory.getBean(ppName,BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);if(pp instanceofMergedBeanDefinitionPostProcessor){
internalPostProcessors.add(pp);}}elseif(beanFactory.isTypeMatch(ppName,Ordered.class)){
orderedPostProcessorNames.add(ppName);}else{
nonOrderedPostProcessorNames.add(ppName);}}// First, register the BeanPostProcessors that implement PriorityOrdered.sortPostProcessors(priorityOrderedPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);// Next, register the BeanPostProcessors that implement Ordered.List<BeanPostProcessor> orderedPostProcessors =newArrayList<>(orderedPostProcessorNames.size());for(String ppName : orderedPostProcessorNames){BeanPostProcessor pp = beanFactory.getBean(ppName,BeanPostProcessor.class);
orderedPostProcessors.add(pp);if(pp instanceofMergedBeanDefinitionPostProcessor){
internalPostProcessors.add(pp);}}sortPostProcessors(orderedPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, orderedPostProcessors);// Now, register all regular BeanPostProcessors.List<BeanPostProcessor> nonOrderedPostProcessors =newArrayList<>(nonOrderedPostProcessorNames.size());for(String ppName : nonOrderedPostProcessorNames){BeanPostProcessor pp = beanFactory.getBean(ppName,BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);if(pp instanceofMergedBeanDefinitionPostProcessor){
internalPostProcessors.add(pp);}}registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);// Finally, re-register all internal BeanPostProcessors.sortPostProcessors(internalPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, internalPostProcessors);// Re-register post-processor for detecting inner beans as ApplicationListeners,// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(newApplicationListenerDetector(applicationContext));}
I18N国际化相关的初始化-initMessageSource()
/**
* Initialize the MessageSource.
* Use parent's if none defined in this context.
*/// 说明:I18N国际化相关的初始化protectedvoidinitMessageSource(){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 instanceofHierarchicalMessageSource){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.isTraceEnabled()){
logger.trace("Using MessageSource ["+this.messageSource +"]");}}else{// Use empty MessageSource to be able to accept getMessage calls.DelegatingMessageSource dms =newDelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME,this.messageSource);if(logger.isTraceEnabled()){
logger.trace("No '"+ MESSAGE_SOURCE_BEAN_NAME +"' bean, using ["+this.messageSource +"]");}}}
initApplicationEventMulticaster()
/**
* Initialize the ApplicationEventMulticaster.
* Uses SimpleApplicationEventMulticaster if none defined in the context.
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/// 说明:初始化事件广播器protectedvoidinitApplicationEventMulticaster(){ConfigurableListableBeanFactory beanFactory =getBeanFactory();if(beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)){this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,ApplicationEventMulticaster.class);if(logger.isTraceEnabled()){
logger.trace("Using ApplicationEventMulticaster ["+this.applicationEventMulticaster +"]");}}else{this.applicationEventMulticaster =newSimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,this.applicationEventMulticaster);if(logger.isTraceEnabled()){
logger.trace("No '"+ APPLICATION_EVENT_MULTICASTER_BEAN_NAME +"' bean, using "+"["+this.applicationEventMulticaster.getClass().getSimpleName()+"]");}}}
registerListeners()
/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
*/// 说明注册监听器protectedvoidregisterListeners(){// 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(!CollectionUtils.isEmpty(earlyEventsToProcess)){for(ApplicationEvent earlyEvent : earlyEventsToProcess){getApplicationEventMulticaster().multicastEvent(earlyEvent);}}}
finishBeanFactoryInitialization()
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/// 说明:非懒加载bean的实例化和初始化protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){// Initialize conversion service for this context.// 说明:类型转换服务,如日期属性类型为Date,xml配置都为string,转换服务可以帮助转成Date对象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(strVal ->getEnvironment().resolvePlaceholders(strVal));}// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.// 说明:aop相关的bean优先初始化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.// 说明:冻结bean definition元数据,不希望后面再去修改了
beanFactory.freezeConfiguration();// Instantiate all remaining (non-lazy-init) singletons.// 说明:真正开始实例化单例bean
beanFactory.preInstantiateSingletons();}
preInstantiateSingletons()
@OverridepublicvoidpreInstantiateSingletons()throwsBeansException{if(logger.isTraceEnabled()){
logger.trace("Pre-instantiating singletons in "+this);}// Iterate over a copy to allow for init methods which in turn register new bean definitions.// While this may not be part of the regular factory bootstrap, it does otherwise work fine.List<String> beanNames =newArrayList<>(this.beanDefinitionNames);// Trigger initialization of all non-lazy singleton beans...// 说明:对每个bean进行实例化和初始化,这里不做展开,后续会在其他文件专门记录如何进行实例化和初始化以及循环依赖的问题for(String beanName : beanNames){RootBeanDefinition bd =getMergedLocalBeanDefinition(beanName);if(!bd.isAbstract()&& bd.isSingleton()&&!bd.isLazyInit()){if(isFactoryBean(beanName)){Object bean =getBean(FACTORY_BEAN_PREFIX + beanName);if(bean instanceofFactoryBean){FactoryBean<?> factory =(FactoryBean<?>) bean;boolean isEagerInit;if(System.getSecurityManager()!=null&& factory instanceofSmartFactoryBean){
isEagerInit =AccessController.doPrivileged((PrivilegedAction<Boolean>)((SmartFactoryBean<?>) factory)::isEagerInit,getAccessControlContext());}else{
isEagerInit =(factory instanceofSmartFactoryBean&&((SmartFactoryBean<?>) factory).isEagerInit());}if(isEagerInit){getBean(beanName);}}}else{getBean(beanName);}}}// Trigger post-initialization callback for all applicable beans...// 说明:最后再执行SmartInitializingSingleton类型的智能初始化方法afterSingletonsInstantiatedfor(String beanName : beanNames){Object singletonInstance =getSingleton(beanName);if(singletonInstance instanceofSmartInitializingSingleton){SmartInitializingSingleton smartSingleton =(SmartInitializingSingleton) singletonInstance;if(System.getSecurityManager()!=null){AccessController.doPrivileged((PrivilegedAction<Object>)()->{
smartSingleton.afterSingletonsInstantiated();returnnull;},getAccessControlContext());}else{
smartSingleton.afterSingletonsInstantiated();}}}}
finishRefresh()
/**
* Finish the refresh of this context, invoking the LifecycleProcessor's
* onRefresh() method and publishing the
* {@link org.springframework.context.event.ContextRefreshedEvent}.
*/// 说明:最后完成刷新容器的方法protectedvoidfinishRefresh(){// Clear context-level resource caches (such as ASM metadata from scanning).// 说明:是否资源缓存clearResourceCaches();// Initialize lifecycle processor for this context.// 说明:初始化一个bean生命周期处理器initLifecycleProcessor();// Propagate refresh to lifecycle processor first.// 说明:对于实现Lifecycle接口的bean调用start()getLifecycleProcessor().onRefresh();// Publish the final event.// 说明:发布刷新完成的事件publishEvent(newContextRefreshedEvent(this));// Participate in LiveBeansView MBean, if active.// 说明:暴露bean信息分享给管理bean的服务MBeanServerLiveBeansView.registerApplicationContext(this);}
resetCommonCaches()
/**
* Reset Spring's common reflection metadata caches, in particular the
* {@link ReflectionUtils}, {@link AnnotationUtils}, {@link ResolvableType}
* and {@link CachedIntrospectionResults} caches.
* @since 4.2
* @see ReflectionUtils#clearCache()
* @see AnnotationUtils#clearCache()
* @see ResolvableType#clearCache()
* @see CachedIntrospectionResults#clearClassLoader(ClassLoader)
*/// 说明:finally块中的最后清理缓存protectedvoidresetCommonCaches(){ReflectionUtils.clearCache();AnnotationUtils.clearCache();ResolvableType.clearCache();CachedIntrospectionResults.clearClassLoader(getClassLoader());}