protectedvoidfinishBeanFactoryInitialization(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.//是用于检查 Bean 工厂是否具有嵌入式值解析器的方法。// 在 Spring 中,嵌入式值解析器用于解析 Bean 定义中的占位符,例如 ${...} 或者 #{...},// 并将其替换为相应的值。通过调用 hasEmbeddedValueResolver() 方法,// 可以判断 Bean 工厂是否已配置嵌入式值解析器,以便在需要时进行值的解析和替换操作。//解析bean中的占位符if(!beanFactory.hasEmbeddedValueResolver()){
beanFactory.addEmbeddedValueResolver(strVal ->getEnvironment().resolvePlaceholders(strVal));}// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.//初始化实现了LoadTimeWeaverAware接口的类 这个用于类加载时织入//类加载时的织入是 AspectJ 的一个特性,允许在类被加载到 JVM 之前应用切面(Aspect)逻辑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.//是用于锁定 Spring 应用程序上下文或 Bean 工厂的配置的方法。在调用 freezeConfiguration() 方法后,// 将无法更改应用程序上下文或 Bean 工厂的配置,这意味着不能再向上下文或 Bean 工厂中添加或更改 Bean 定义、修改属性、或在上下文中加载新的配置文件等。//一旦调用了 freezeConfiguration() 方法,应用程序上下文或 Bean 工厂就被认为是只读的,并且可以在多线程环境中安全地使用。// 这个方法在应用程序上下文或 Bean 工厂初始化完成后调用,以确保配置的完整性和不可更改性。
beanFactory.freezeConfiguration();// Instantiate all remaining (non-lazy-init) singletons.//是用于预初始化单例 Bean 的方法。在 Spring 容器启动时,如果某些 Bean 的作用域为 Singleton,// 且其 lazy-init 属性为 false,那么 Spring 会在容器初始化的过程中自动对这些 Bean 进行实例化。// 但是,如果你想在容器初始化的早期手动触发所有单例 Bean 的实例化过程,// 你可以调用 preInstantiateSingletons() 方法。//调用 preInstantiateSingletons() 方法将导致容器立即实例化所有标记为 Singleton 且非懒加载的 Bean,// 以确保这些 Bean 在容器生命周期的早期阶段就已经被创建。这个方法通常在 Spring 容器启动后的某个时刻被调用,// 它可以保证当你需要使用某些 Singleton Bean 时,它们已经被完全创建和初始化。// 这样可以避免在运行时因为延迟实例化而产生的潜在性能问题或并发问题。
beanFactory.preInstantiateSingletons();}
publicvoidpreInstantiateSingletons()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.//拿到所有的beanNameList<String> beanNames =newArrayList<>(this.beanDefinitionNames);// Trigger initialization of all non-lazy singleton beans...//初始化非懒加载的beanfor(String beanName : beanNames){//将bean进行合并处理之后返回 RootBeanDefinition 作为最终初始化的bean使用RootBeanDefinition bd =getMergedLocalBeanDefinition(beanName);//bd 不是抽象类 && 是单例的 && 不是懒加载的if(!bd.isAbstract()&& bd.isSingleton()&&!bd.isLazyInit()){if(isFactoryBean(beanName)){//判断当前bean是一个FactoryBean//回去FactoryBean对象本身Object bean =getBean(FACTORY_BEAN_PREFIX+ beanName);if(bean instanceofFactoryBean){//判断当前bean的类型是FactoryBeanFactoryBean<?> factory =(FactoryBean<?>) bean;boolean isEagerInit;if(System.getSecurityManager()!=null&& factory instanceofSmartFactoryBean){
isEagerInit =AccessController.doPrivileged((PrivilegedAction<Boolean>)((SmartFactoryBean<?>) factory)::isEagerInit,getAccessControlContext());}else{//判断bean 是否需要更早期的初始化
isEagerInit =(factory instanceofSmartFactoryBean&&((SmartFactoryBean<?>) factory).isEagerInit());}//为true 则在容器启动时立即初始化if(isEagerInit){getBean(beanName);}}}else{getBean(beanName);}}}// Trigger post-initialization callback for all applicable beans...for(String beanName : beanNames){//再次遍历所有的已创建和的单例beanObject singletonInstance =getSingleton(beanName);//获取单例bean 并且判断该bean的类型是SmartInitializingSingletonif(singletonInstance instanceofSmartInitializingSingleton){SmartInitializingSingleton smartSingleton =(SmartInitializingSingleton) singletonInstance;if(System.getSecurityManager()!=null){AccessController.doPrivileged((PrivilegedAction<Object>)()->{
smartSingleton.afterSingletonsInstantiated();returnnull;},getAccessControlContext());}else{//则调用afterSingletonsInstantiated方法
smartSingleton.afterSingletonsInstantiated();}}}}
protectedRootBeanDefinitiongetMergedBeanDefinition(String beanName,BeanDefinition bd,@NullableBeanDefinition containingBd)throwsBeanDefinitionStoreException{synchronized(this.mergedBeanDefinitions){RootBeanDefinition mbd =null;// Check with full lock now in order to enforce the same merged instance.if(containingBd ==null){//从合并bean缓存中获取
mbd =this.mergedBeanDefinitions.get(beanName);}if(mbd ==null){//如果不存在if(bd.getParentName()==null){//判断当前bean的是否父bean不存在// Use copy of given root bean definition.if(bd instanceofRootBeanDefinition){//并且当前的类型是RootBeanDefinition 则克隆一个
mbd =((RootBeanDefinition) bd).cloneBeanDefinition();}else{//否则创建一个新的RootBeanDefinition
mbd =newRootBeanDefinition(bd);}}else{// Child bean definition: needs to be merged with parent.BeanDefinition pbd;try{//如果存在父beanString parentBeanName =transformedBeanName(bd.getParentName());if(!beanName.equals(parentBeanName)){//递归调用父bean的bean
pbd =getMergedBeanDefinition(parentBeanName);}else{//从工厂中获取父beanBeanFactory parent =getParentBeanFactory();if(parent instanceofConfigurableBeanFactory){
pbd =((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);}else{thrownewNoSuchBeanDefinitionException(parentBeanName,"Parent name '"+ parentBeanName +"' is equal to bean name '"+ beanName +"': cannot be resolved without a ConfigurableBeanFactory parent");}}}catch(NoSuchBeanDefinitionException ex){thrownewBeanDefinitionStoreException(bd.getResourceDescription(), beanName,"Could not resolve parent bean definition '"+ bd.getParentName()+"'", ex);}// Deep copy with overridden values.//创建一个新的RootBeanDefinition
mbd =newRootBeanDefinition(pbd);
mbd.overrideFrom(bd);}// Set default singleton scope, if not configured before.if(!StringUtils.hasLength(mbd.getScope())){//设置bean的作用域
mbd.setScope(SCOPE_SINGLETON);}// A bean contained in a non-singleton bean cannot be a singleton itself.// Let's correct this on the fly here, since this might be the result of// parent-child merging for the outer bean, in which case the original inner bean// definition will not have inherited the merged outer bean's singleton status.if(containingBd !=null&&!containingBd.isSingleton()&& mbd.isSingleton()){//使用之前的scope
mbd.setScope(containingBd.getScope());}// Cache the merged bean definition for the time being// (it might still get re-merged later on in order to pick up metadata changes)if(containingBd ==null&&isCacheBeanMetadata()){//将新的合并好的bean放入缓存中this.mergedBeanDefinitions.put(beanName, mbd);}}//如果存在 则直接返回return mbd;}}