// Prepare this context for refreshing. prepareRefresh();
// Tell the subclass to refresh the internal bean factory. // 工厂创建:BeanFactory第一次开始创建的时候,有xml解析逻辑。 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory);
try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process"); //工厂增强:执行所有的BeanFactory后置增强器;利用BeanFactory后置增强器对工厂进行修改或者增强,配置类会在这里进行解析。 Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory);
//注册所有的Bean的后置处理器 Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); beanPostProcess.end();
// Initialize message source for this context. initMessageSource();
// Initialize event multicaster for this context. initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses. onRefresh();
//注册监听器,从容器中获取所有的ApplicationListener; Check for listener beans and register them. registerListeners();
// Instantiate all remaining (non-lazy-init) singletons. //bean创建;完成 BeanFactory 初始化。(工厂里面所有的组件都好了) finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event. finishRefresh(); }
// 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(); contextRefresh.end(); } } }
protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){ // 给工厂设置好 ConversionService【负责类型转换的组件服务】, 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 BeanFactoryPostProcessor // (such as a PropertySourcesPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }
// LoadTimeWeaverAware;aspectj:加载时织入功能【aop】。 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. //初始化所有的非懒加载的单实例Bean beanFactory.preInstantiateSingletons(); }
publicvoidpreInstantiateSingletons()throws BeansException { 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 = new ArrayList<>(this.beanDefinitionNames);
//获取某一个组件在容器中的名字。 工厂Bean的主要逻辑还是走到这里,这里我们之前讲过 private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { List<String> result = new ArrayList<>();
// Check all bean definitions. 因为Spring没有直接保存class--bean名字的对应信息,只能遍历所有的beanname,拿出他们beanname的定义信息,再看是否我指定的类型。 for (String beanName : this.beanDefinitionNames) { // Only consider bean as eligible if the bean name is not defined as alias for some other bean. if (!isAlias(beanName)) { //判断是否别名 try { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Only check bean definition if it is complete. if (!mbd.isAbstract() && (allowEagerInit || (mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) && !requiresEagerInitForType(mbd.getFactoryBeanName()))) { boolean isFactoryBean = isFactoryBean(beanName, mbd); //是否FactoryBean BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); boolean matchFound = false; boolean allowFactoryBeanInit = (allowEagerInit || containsSingleton(beanName)); boolean isNonLazyDecorated = (dbd != null && !mbd.isLazyInit()); if (!isFactoryBean) { if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) { matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit); //是否类型匹配? } } else { if (includeNonSingletons || isNonLazyDecorated || (allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) { matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit); } if (!matchFound) { // In case of FactoryBean, try to match FactoryBean instance itself next. beanName = FACTORY_BEAN_PREFIX + beanName; matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit); } } if (matchFound) { result.add(beanName); } } } catch (CannotLoadBeanClassException | BeanDefinitionStoreException ex) { if (allowEagerInit) { throw ex; } // Probably a placeholder: let's ignore it for type matching purposes. LogMessage message = (ex instanceof CannotLoadBeanClassException ? LogMessage.format("Ignoring bean class loading failure for bean '%s'", beanName) : LogMessage.format("Ignoring unresolvable metadata in bean definition '%s'", beanName)); logger.trace(message, ex); // Register exception, in case the bean was accidentally unresolvable. onSuppressedException(ex); } catch (NoSuchBeanDefinitionException ex) { // Bean definition got removed while we were iterating -> ignore. } } }
// Check manually registered singletons too. for (String beanName : this.manualSingletonNames) { try { // In case of FactoryBean, match object created by FactoryBean. if (isFactoryBean(beanName)) { if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) { result.add(beanName); // Match found for this bean: do not match FactoryBean itself anymore. continue; } // In case of FactoryBean, try to match FactoryBean itself next. beanName = FACTORY_BEAN_PREFIX + beanName;//注意这里的工厂Bean前缀 } // Match raw bean instance (might be raw FactoryBean). if (isTypeMatch(beanName, type)) { result.add(beanName); } } catch (NoSuchBeanDefinitionException ex) { // Shouldn't happen - probably a result of circular reference resolution... logger.trace(LogMessage.format( "Failed to check manually registered singleton with name '%s'", beanName), ex); } }
// 先检查单实例bean的缓存 Eagerly check singleton cache for manually registered singletons. Object sharedInstance = getSingleton(beanName); //检查缓存中有没有,如果是第一次获取肯定是没有的 if (sharedInstance != null && args == null) { if (logger.isTraceEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); } } beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null); }
else { //默认第一次获取组件都会进入else环节 // Fail if we're already creating this bean instance: // We're assumably within a circular reference. if (isPrototypeCurrentlyInCreation(beanName)) { thrownew BeanCurrentlyInCreationException(beanName); }
// 拿到整个beanFactory的父工厂;看父工厂没有,从父工厂先尝试获取组件; Check if bean definition exists in this factory. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //以下开始从父工厂获取组件 // Not found -> check parent. // ... }
if (!typeCheckOnly) { markBeanAsCreated(beanName); //标记当前beanName的bean已经被创建 }
// Guarantee initialization of beans that the current bean depends on. String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { //看当前Bean有没有依赖其他Bean if (isDependent(beanName, dep)) { thrownew BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } registerDependentBean(dep, beanName); try { getBean(dep); //依赖了其他bean,就先获取其他的哪些bean } catch (NoSuchBeanDefinitionException ex) { thrownew BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } }
// 创建bean的实例;Create bean instance. if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { return createBean(beanName, mbd, args); //创建bean对象的实例 } 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; } }); //看当前bean是否是FactoryBean beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } elseif (mbd.isPrototype()) { // ... } else{} // ... //转Object为Bean的T类型 return adaptBeanInstance(name, beanInstance, requiredType); }
protectedvoidmarkBeanAsCreated(String beanName){ if (!this.alreadyCreated.contains(beanName)) { synchronized (this.mergedBeanDefinitions) { if (!this.alreadyCreated.contains(beanName)) { // Let the bean definition get re-merged now that we're actually creating // the bean... just in case some of its metadata changed in the meantime. clearMergedBeanDefinition(beanName); this.alreadyCreated.add(beanName); } } } } // 已经创建了的Bean名字池。Spring内部有很多这样记录Bean状态的集合(池子) /** Names of beans that have already been created at least once. */ privatefinal Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));
@Override @Nullable public Object getSingleton(String beanName){ return getSingleton(beanName, true); }
//下面的代码是解决循环依赖的核心,后面细讲 @Nullable protected Object getSingleton(String beanName, boolean allowEarlyReference){ //先检查单例缓存池,获取当前对象 Quick check for existing instance without full singleton lock Object singletonObject = this.singletonObjects.get(beanName); //一级缓存 if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { //如果当前bean正在创建过程中,而且缓存中没有则继续 singletonObject = this.earlySingletonObjects.get(beanName); //二级 if (singletonObject == null && allowEarlyReference) { synchronized (this.singletonObjects) { // Consistent creation of early reference within full singleton lock singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null) { ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); //三级 if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } } } } } } return singletonObject; }
/** 享元模式的单例。缓存所有单实例对象,单例对象池。ioc容器-单例池; Cache of singleton objects: bean name to bean instance. */ privatefinal Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
// 正在创建的组件的名字池 /** Names of beans that are currently in creation. */ privatefinal Set<String> singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap<>(16));
AbstractBeanFactory#doGetBean()创建Bean的核心代码
// 创建bean的实例;Create bean instance. if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { return createBean(beanName, mbd, args); //创建bean对象的实例 } 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; } }); //看当前bean是否是FactoryBean beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); }
这里是创建Bean的核心,就是一个lamda表达式
DefaultSingletonBeanRegistry#getSingleton()
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory){ Assert.notNull(beanName, "Bean name must not be null"); synchronized (this.singletonObjects) { Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { //单实例池子里面没有当前对象(说明没有创建完成) if (this.singletonsCurrentlyInDestruction) { thrownew BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while singletons of this factory are in destruction " + "(Do not request a bean from a BeanFactory in a destroy method implementation!)"); } if (logger.isDebugEnabled()) { logger.debug("Creating shared instance of singleton bean '" + beanName + "'"); } beforeSingletonCreation(beanName); //单实例创建之前 boolean newSingleton = false; boolean recordSuppressedExceptions = (this.suppressedExceptions == null); if (recordSuppressedExceptions) { this.suppressedExceptions = new LinkedHashSet<>(); } try { /* 1.这里会调用lamda表达式的内容,真正创建对象,也就是调用creatbean, 2.ObjectFactory类注释上写了这里类似于一个工厂Bean,所以这里写的和工厂bean一样的getObject()。我们 在前面是这样讲的 3.但实际上ObjectFactory就是一个@FunctionalInterface标注的函数式接口,你调用它唯一的getObject(),那么 当然就会调用createbean了。(这里就涉及lamda表达式的知识了,不知道的建议自行补习) */ singletonObject = singletonFactory.getObject(); newSingleton = true; } catch (IllegalStateException ex) { // Has the singleton object implicitly appeared in the meantime -> // if yes, proceed with it since the exception indicates that state. singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { throw ex; } } catch (BeanCreationException ex) { if (recordSuppressedExceptions) { for (Exception suppressedException : this.suppressedExceptions) { ex.addRelatedCause(suppressedException); } } throw ex; } finally { if (recordSuppressedExceptions) { this.suppressedExceptions = null; } afterSingletonCreation(beanName); } if (newSingleton) { addSingleton(beanName, singletonObject); } } return singletonObject; } }
if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); }