bean 的实例化有如下几种方法
静态方法工厂方法创建FactoryBean 接口创建获取beanFactory
获取方法是一个抽象方法
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;子类实现
org.springframework.context.support.AbstractRefreshableApplicationContext#getBeanFactory
@Override public final ConfigurableListableBeanFactory getBeanFactory() { synchronized (this.beanFactoryMonitor) { if (this.beanFactory == null) { throw new IllegalStateException("BeanFactory not initialized or already closed - " + "call 'refresh' before accessing beans via the ApplicationContext"); } return this.beanFactory; } } org.springframework.context.support.GenericApplicationContext#getBeanFactory @Override public final ConfigurableListableBeanFactory getBeanFactory() { return this.beanFactory; }获取到的对象是org.springframework.beans.factory.support.DefaultListableBeanFactory
整体类图org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
获取 bean 的核心
别名对象
private final Map<String, String> aliasMap = new ConcurrentHashMap<>(16); <bean id="factory-bean-user" class="org.source.hot.spring.overview.ioc.bean.init.UserFactoryBean"/> <alias name="factory-bean-user" alias="userFactoryBean"/>aliasMap 和 别名标签的对应关系
alias标签的alias值作为别名的key , alias 标签的 name 值作为 value
org.springframework.beans.factory.support.FactoryBeanRegistrySupport#getObjectFromFactoryBean
从 FactoryBean 中获取对象
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) { // 是否单例 是否已经包含 if (factory.isSingleton() && containsSingleton(beanName)) { synchronized (getSingletonMutex()) { // 从工厂bean的缓存中获取 Object object = this.factoryBeanObjectCache.get(beanName); if (object == null) { // 从 factoryBean 接口中获取 object = doGetObjectFromFactoryBean(factory, beanName); // Only post-process and store if not put there already during getObject() call above // (e.g. because of circular reference processing triggered by custom getBean calls) // 从缓存map中获取 Object alreadyThere = this.factoryBeanObjectCache.get(beanName); if (alreadyThere != null) { // 如果缓存中获取有值 // object 覆盖 object = alreadyThere; } else { if (shouldPostProcess) { if (isSingletonCurrentlyInCreation(beanName)) { // Temporarily return non-post-processed object, not storing it yet.. return object; } // 单例创建前的验证 beforeSingletonCreation(beanName); try { // 从 FactoryBean 接口创建的 后置处理 object = postProcessObjectFromFactoryBean(object, beanName); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of FactoryBean's singleton object failed", ex); } finally { // 单例bean创建之后 afterSingletonCreation(beanName); } } // 是否包含bean name if (containsSingleton(beanName)) { // 插入缓存 // 后续使用的时候可以直接获取 this.factoryBeanObjectCache.put(beanName, object); } } } return object; } } else { Object object = doGetObjectFromFactoryBean(factory, beanName); if (shouldPostProcess) { try { object = postProcessObjectFromFactoryBean(object, beanName); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex); } } return object; } }org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#beforeSingletonCreation
单例创建前的验证
protected void beforeSingletonCreation(String beanName) { // 排除的单例beanName 是否包含当前beanName // 添加当前正在初始化的beanName 是否正确 if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } }两种实现
org.springframework.beans.factory.support.FactoryBeanRegistrySupport#postProcessObjectFromFactoryBean
protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException { return object; }直接返回 object
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#postProcessObjectFromFactoryBean 调用 BeanPostProcessor
@Override protected Object postProcessObjectFromFactoryBean(Object object, String beanName) { return applyBeanPostProcessorsAfterInitialization(object, beanName); } @Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }两个方法军返回 Bean 对象 . 一种是直接返回 。 另一种是执行接口 BeanPostProcessor 接口返回
目前未知doGetBean的第一个if分支已经分析完毕. 接下来看下面的代码
下面这段代码就简单说一下就跳过了。
从 容器中获取,最后还是回到doGetBean方法中. 来进行bean创建 这里不进行展开。 else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. // 循环依赖的问题 if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // Check if bean definition exists in this factory. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. String nameToLookup = originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } else if (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else if (requiredType != null) { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } else { return (T) parentBeanFactory.getBean(nameToLookup); } }org.springframework.beans.factory.support.AbstractBeanFactory#markBeanAsCreated
方法作用将bean标记为已创建
protected void markBeanAsCreated(String beanName) { // 已创建的beanName 是否包含当前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. // 将属性stale设置true clearMergedBeanDefinition(beanName); // 放入已创建集合中 this.alreadyCreated.add(beanName); } } } } protected void clearMergedBeanDefinition(String beanName) { RootBeanDefinition bd = this.mergedBeanDefinitions.get(beanName); if (bd != null) { bd.stale = true; } }stale 的解释
/** * Determines if the definition needs to be re-merged. * 是否需要重新合并定义 * */ volatile boolean stale;属性值 已创建的beanName
private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));org.springframework.beans.factory.support.AbstractBeanFactory#getMergedLocalBeanDefinition
这个方法获取一个RootBeanDefinition对象 , 这个对象也是bean的一种定义。
从目前的几个方法名称来看,暂且认为这是一个合并了多个 BeanDefinition的对象吧
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException { // Quick check on the concurrent map first, with minimal locking. // 缓存中获取 RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName); if (mbd != null && !mbd.stale) { return mbd; } // 合并的 bean 定义 return getMergedBeanDefinition(beanName, getBeanDefinition(beanName)); } protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd) throws BeanDefinitionStoreException { return getMergedBeanDefinition(beanName, bd, null); }从 beanDefinition map 中获取
相关属性
/** * Map of bean definition objects, keyed by bean name. * * key: beanName * value: BeanDefinition * * */ private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);获取RootBeanDefinition
org.springframework.beans.factory.support.AbstractBeanFactory#getMergedBeanDefinition(java.lang.String, org.springframework.beans.factory.config.BeanDefinition, org.springframework.beans.factory.config.BeanDefinition)
第一部分代码
map 中获取 RootBeanDefinition是否存在父名称类型是否是 RootBeanDefinition 是: 拷贝否: 将 BeanDefinition 转换成 RootBeanDefinition protected RootBeanDefinition getMergedBeanDefinition( String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd) throws BeanDefinitionStoreException { synchronized (this.mergedBeanDefinitions) { RootBeanDefinition mbd = null; RootBeanDefinition previous = null; // Check with full lock now in order to enforce the same merged instance. if (containingBd == null) { // 从缓存中获取 mbd = this.mergedBeanDefinitions.get(beanName); } if (mbd == null || mbd.stale) { previous = mbd; // 是否存在父名称 if (bd.getParentName() == null) { // Use copy of given root bean definition. // 类型是否等于RootBeanDefinition if (bd instanceof RootBeanDefinition) { // 做一次对象拷贝 mbd = ((RootBeanDefinition) bd).cloneBeanDefinition(); } else { // 将 beanDefinition 创建成 RootBeanDefinition mbd = new RootBeanDefinition(bd); } } // 省略其他 }相关属性
/** * Map from bean name to merged RootBeanDefinition. * key: beanName * value: RootBeanDefinition * */ private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256);克隆 方法
/** * 克隆 BeanDefinition * @return */ @Override public RootBeanDefinition cloneBeanDefinition() { return new RootBeanDefinition(this); }第二部分代码
{ // Child bean definition: needs to be merged with parent. // 父BeanDefinition BeanDefinition pbd; try { // 父类beanName String parentBeanName = transformedBeanName(bd.getParentName()); // 当前beanName是否等于父的beanName if (!beanName.equals(parentBeanName)) { // 存在父 beanName // 父 beanDefinition // 递归调用 pbd = getMergedBeanDefinition(parentBeanName); } else { // 获取父 beanFactory BeanFactory parent = getParentBeanFactory(); // beanFactory 类型判断 if (parent instanceof ConfigurableBeanFactory) { // ConfigurableBeanFactory 的获取方式 pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName); } else { throw new NoSuchBeanDefinitionException(parentBeanName, "Parent name '" + parentBeanName + "' is equal to bean name '" + beanName + "': cannot be resolved without an AbstractBeanFactory parent"); } } } catch (NoSuchBeanDefinitionException ex) { throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName, "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex); } // Deep copy with overridden values. // 将 父 BeanDefinition 对象拷贝 mbd = new RootBeanDefinition(pbd); // 覆盖 beanDefinition mbd.overrideFrom(bd); }覆盖方法
org.springframework.beans.factory.support.AbstractBeanDefinition#overrideFrom
最后一段
// Set default singleton scope, if not configured before. // 作用域设置 if (!StringUtils.hasLength(mbd.getScope())) { // 没有设置作用域直接给单例类型 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()) { 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()) { // 放入缓存 this.mergedBeanDefinitions.put(beanName, mbd); } } if (previous != null) { copyRelevantMergedBeanDefinitionCaches(previous, mbd); } return mbd;org.springframework.beans.factory.support.AbstractBeanFactory#checkMergedBeanDefinition
protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, @Nullable Object[] args) throws BeanDefinitionStoreException { if (mbd.isAbstract()) { throw new BeanIsAbstractException(beanName); } } 判断是否 abstract 标记的情况继续回到 doGetBean 方法
// 需要依赖的bean String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } // 注册依赖bean registerDependentBean(dep, beanName); try { getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } }是否存在依赖关系
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#isDependent(java.lang.String, java.lang.String, java.util.Set<java.lang.String>)
private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) { if (alreadySeen != null && alreadySeen.contains(beanName)) { return false; } // 别名 String canonicalName = canonicalName(beanName); // 依赖列表中获取 Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName); if (dependentBeans == null) { return false; } if (dependentBeans.contains(dependentBeanName)) { return true; } for (String transitiveDependency : dependentBeans) { if (alreadySeen == null) { alreadySeen = new HashSet<>(); } alreadySeen.add(beanName); if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) { return true; } } return false; }相关属性
/** * Map between dependent bean names: bean name to Set of dependent bean names. * * key: bean * value: 依赖列表 * */ private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);一个用例
<bean class="org.source.hot.spring.overview.ioc.bean.init.SystemUserBean" > <property name="userBean" ref="factory-use"/> </bean>再回到 doGetBean
接下来就是实例化的过程了.
if (mbd.isSingleton()) { 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; } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); }org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, org.springframework.beans.factory.ObjectFactory<?>)
获取单例对象
从单例对象的map缓存中获取从 ObjectFactory 中获取周边方法
beforeSingletonCreation
afterSingletonCreation
addSingleton
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) { throw new 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 { // 从 ObjectFactory 中获取 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; } }回到 doGetBean 方法中
if (mbd.isSingleton()) { // 判断是否是单例 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; } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); }这里又要给 createBean方法, 从 getSingleton 的参数看可以知道 ,第二个匿名函数是ObjectFactory接口实现.
@FunctionalInterface public interface ObjectFactory<T> { /** * Return an instance (possibly shared or independent) * of the object managed by this factory. * 获取对象 * @return the resulting instance * @throws BeansException in case of creation errors */ T getObject() throws BeansException; } createBean 返回的就是单例bean对象的实例org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
两个核心方法
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. Object bean = resolveBeforeInstantiation(beanName, mbdToUse); Object beanInstance = doCreateBean(beanName, mbdToUse, args);org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation
方法概述:
获取BeanPostProcessor接口的实现列表
applyBeanPostProcessorsBeforeInstantiation 前置方法执行applyBeanPostProcessorsAfterInitialization后置方法执行 @Nullable protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { Object bean = null; if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { // Make sure bean class is actually resolved at this point. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { Class<?> targetType = determineTargetType(beanName, mbd); if (targetType != null) { /** * 主要实现{@link org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation(java.lang.Class, java.lang.String)} */ bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); if (bean != null) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } mbd.beforeInstantiationResolved = (bean != null); } return bean; }org.springframework.beans.factory.support.AbstractBeanFactory#doResolveBeanClass
第一段
ClassLoader beanClassLoader = getBeanClassLoader(); ClassLoader dynamicLoader = beanClassLoader; boolean freshResolve = false; // 判断 typesToMatch 是否为空 if (!ObjectUtils.isEmpty(typesToMatch)) { // When just doing type checks (i.e. not creating an actual instance yet), // use the specified temporary class loader (e.g. in a weaving scenario). // 获取临时类加载器 ClassLoader tempClassLoader = getTempClassLoader(); if (tempClassLoader != null) { dynamicLoader = tempClassLoader; freshResolve = true; // 类型比较 if (tempClassLoader instanceof DecoratingClassLoader) { DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader; for (Class<?> typeToMatch : typesToMatch) { // 添加排除的类 dcl.excludeClass(typeToMatch.getName()); } } } }第二段
if (className != null) { // bean 属性值 Object evaluated = evaluateBeanDefinitionString(className, mbd); if (!className.equals(evaluated)) { // A dynamically resolved expression, supported as of 4.2... if (evaluated instanceof Class) { return (Class<?>) evaluated; } else if (evaluated instanceof String) { className = (String) evaluated; freshResolve = true; } else { throw new IllegalStateException("Invalid class name expression result: " + evaluated); } }beanName 是否存在
根据 beanName 获取 bean 实例
回到解析方法doParseExpression
spring 中的两种解析方式 org.springframework.expression.spel.standard.InternalSpelExpressionParser#doParseExpressionorg.springframework.expression.spel.standard.SpelExpressionParser#doParseExpressionparseTemplate 方法
org.springframework.expression.common.TemplateAwareExpressionParser#parseTemplate private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException { // 表达式为空 if (expressionString.isEmpty()) { // 创建空的 LiteralExpression return new LiteralExpression(""); } // 表达式解析成接口 Expression[] expressions = parseExpressions(expressionString, context); if (expressions.length == 1) { return expressions[0]; } else { // 返回字符串的表达式 return new CompositeStringExpression(expressionString, expressions); } }parseExpressions
org.springframework.expression.common.TemplateAwareExpressionParser#parseExpressions说简单一些这个地方就是拿出表达式的值回到 evaluate 方法
StandardEvaluationContext sec = this.evaluationCache.get(evalContext); if (sec == null) { // 设置属性 sec = new StandardEvaluationContext(evalContext); sec.addPropertyAccessor(new BeanExpressionContextAccessor()); sec.addPropertyAccessor(new BeanFactoryAccessor()); sec.addPropertyAccessor(new MapAccessor()); sec.addPropertyAccessor(new EnvironmentAccessor()); sec.setBeanResolver(new BeanFactoryResolver(evalContext.getBeanFactory())); sec.setTypeLocator(new StandardTypeLocator(evalContext.getBeanFactory().getBeanClassLoader())); ConversionService conversionService = evalContext.getBeanFactory().getConversionService(); if (conversionService != null) { sec.setTypeConverter(new StandardTypeConverter(conversionService)); } customizeEvaluationContext(sec); this.evaluationCache.put(evalContext, sec); } // 把值获取 return expr.getValue(sec);最后一句 getValue
org.springframework.expression.common.LiteralExpression#getValue(org.springframework.expression.EvaluationContext)
刚才流程中我们可以看到 expr 是LiteralExpression
@Override public String getValue(EvaluationContext context) { return this.literalValue; }直接返回字符串. 这个字符串就是刚才放进去的 el表达式
往外跳 找到方法 doResolveBeanClass
if (className != null) { // bean 属性值 Object evaluated = evaluateBeanDefinitionString(className, mbd); if (!className.equals(evaluated)) { // A dynamically resolved expression, supported as of 4.2... if (evaluated instanceof Class) { return (Class<?>) evaluated; } else if (evaluated instanceof String) { className = (String) evaluated; freshResolve = true; } else { throw new IllegalStateException("Invalid class name expression result: " + evaluated); } } if (freshResolve) { // When resolving against a temporary class loader, exit early in order // to avoid storing the resolved Class in the bean definition. if (dynamicLoader != null) { try { return dynamicLoader.loadClass(className); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("Could not load class [" + className + "] from " + dynamicLoader + ": " + ex); } } } return ClassUtils.forName(className, dynamicLoader); } } 目前为止我们解析了 第一句话 Object evaluated = evaluateBeanDefinitionString(className, mbd); 接下来往下走看一下具体的 class 返回对象 类型等于 class 直接返回类型等于 String 的两种返回方式 ClassLoader.loadClass 返回ClassUtils.forName 返回 底层方法为 java.lang.Class#forName(java.lang.String, boolean, java.lang.ClassLoader)回到doResolveBeanClass方法中.最后一行
// Resolve regularly, caching the result in the BeanDefinition... return mbd.resolveBeanClass(beanClassLoader); @Nullable public Class<?> resolveBeanClass(@Nullable ClassLoader classLoader) throws ClassNotFoundException { // 获取beanClassName String className = getBeanClassName(); if (className == null) { return null; } // 加载类 Class<?> resolvedClass = ClassUtils.forName(className, classLoader); this.beanClass = resolvedClass; // 返回 return resolvedClass; } 获取 beanClassName @Override @Nullable public String getBeanClassName() { Object beanClassObject = this.beanClass; if (beanClassObject instanceof Class) { return ((Class<?>) beanClassObject).getName(); } else { return (String) beanClassObject; } } 回到createBeanInstance org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance // 返回一个用来创建bean实例的回调接口 // Supplier get 直接获取bean对象 Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); if (instanceSupplier != null) { return obtainFromSupplier(instanceSupplier, beanName); }最后调用
org.springframework.beans.support.ResourceEditorRegistrar#registerCustomEditors
覆盖默认编辑器
public void overrideDefaultEditor(Class<?> requiredType, PropertyEditor propertyEditor) { if (this.overriddenDefaultEditors == null) { this.overriddenDefaultEditors = new HashMap<>(); } this.overriddenDefaultEditors.put(requiredType, propertyEditor); } registerCustomEditor @Override public void registerCustomEditor(@Nullable Class<?> requiredType, @Nullable String propertyPath, PropertyEditor propertyEditor) { if (requiredType == null && propertyPath == null) { throw new IllegalArgumentException("Either requiredType or propertyPath is required"); } if (propertyPath != null) { if (this.customEditorsForPath == null) { this.customEditorsForPath = new LinkedHashMap<>(16); } this.customEditorsForPath.put(propertyPath, new CustomEditorHolder(propertyEditor, requiredType)); } else { if (this.customEditors == null) { this.customEditors = new LinkedHashMap<>(16); } // 放入 customEditors map对象中 this.customEditors.put(requiredType, propertyEditor); this.customEditorCache = null; } }到这里 createBeanInstance 流程已经完毕
回到doCreateBean 方法
// beanWrapper 是否存在 if (instanceWrapper == null) { // 创建 bean 实例 instanceWrapper = createBeanInstance(beanName, mbd, args); } // 获取 实例 final Object bean = instanceWrapper.getWrappedInstance(); // beanWrapper中存储的实例.class Class<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType; }紧接着两行代码 获取 bean 实例 和beanType
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingletonFactory
继续回到 doCreateBean
// Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); // 单例对象暴露 if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); }org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingletonFactory
添加单例工厂
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(singletonFactory, "Singleton factory must not be null"); synchronized (this.singletonObjects) { if (!this.singletonObjects.containsKey(beanName)) { // 添加单例对象工厂 this.singletonFactories.put(beanName, singletonFactory); // 删除单例BeanName this.earlySingletonObjects.remove(beanName); // 注册单例beanName this.registeredSingletons.add(beanName); } } }回到下面代码中
if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } // 添加单例工厂 addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } 上述方法就是将结果bean放入org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
设置属性值
概述一下方法
自动注入的两种实现
根据类型根据名称xml 中的属性标签设置
<bean class="org.source.hot.spring.overview.ioc.bean.init.UserBean"> <property name="age" value="30"/> </bean> { if (bw == null) { if (mbd.hasPropertyValues()) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. return; } } // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } } PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); // 获取自动注入的值 int resolvedAutowireMode = mbd.getResolvedAutowireMode(); // 自动注入 if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { // 按照名称注入 autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { // 按照类型注入 autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); PropertyDescriptor[] filteredPds = null; if (hasInstAwareBpps) { if (pvs == null) { pvs = mbd.getPropertyValues(); } for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { return; } } pvs = pvsToUse; } } } if (needsDepCheck) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } // 以来检查 checkDependencies(beanName, mbd, filteredPds, pvs); } if (pvs != null) { // 应用属性 applyPropertyValues(beanName, mbd, bw, pvs); } }pvs 属性如下
属性设置后跳出方法回到 doCreateBean
try { populateBean(beanName, mbd, instanceWrapper); exposedObject = initializeBean(beanName, exposedObject, mbd); }org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)
我们可以看一下整个代码的流程
aware 接口的执行BeanPostProcessor 前置方法执行bean实例化BeanPostProcessor 后置方法执行返回bean protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareMethods(beanName, bean); return null; }, getAccessControlContext()); } else { // aware 接口执行 invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { // BeanPostProcessor 前置方法执行 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { // 执行实例化函数 invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex ); } if (mbd == null || !mbd.isSynthetic()) { // BeanPostProcessor 后置方法执行 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; } Aware 接口的执行 private void invokeAwareMethods(final String beanName, final Object bean) { if (bean instanceof Aware) { if (bean instanceof BeanNameAware) { ((BeanNameAware) bean).setBeanName(beanName); } if (bean instanceof BeanClassLoaderAware) { ClassLoader bcl = getBeanClassLoader(); if (bcl != null) { ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl); } } if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this); } } }j前置方法执行
@Override public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessBeforeInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }后置方法执行
@Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { // 执行 spring 容器中 BeanPostProcessor Object current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }我们现在的bean不是InitializingBean 会走自定义的init-mthod方法
做一下改造实体对象
public void initMethod() { this.name = "abc"; this.age = 10; } <bean class="org.source.hot.spring.overview.ioc.bean.init.UserBean" init-method="initMethod"> <property name="age" value="30"/> </bean> 观察 initMethodName 会变成 标签属性init-method 的内容. 接下来就是通过反射执行方法在执行方法前将 bean 的信息先做一次截图
如果按照我们代码中的编写方式 bean 的属性会被覆盖
跳出这个方法initializeBean 回到下面代码
try { populateBean(beanName, mbd, instanceWrapper); exposedObject = initializeBean(beanName, exposedObject, mbd); }org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
其实到此bean已经创建完成可以直接返回了.
再往外层跳
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
if (mbd.isSingleton()) { // 判断是否是单例 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; } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } 单例对象的创建bean已经完成啦…其他的两种创建,其本质还是 createBean 方法的调用.
// 原型模式创建 else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName); prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } }再往外面跳一层 回到 getBean 方法.
终于 getBean 方法底层调用分析结束.