抽象類AbstractAutowireCapableBeanFactory繼承了AbstractBeanFactory類,以及實現了AutowireCapableBeanFactory的接口。segmentfault
// bean的生成策略,默認CGLIB private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy(); // 解析策略的方法參數 private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); // 嘗試解析循環引用 private boolean allowCircularReferences = true; // 在循環引用的狀況下,是否須要注入一個原始的bean實例 private boolean allowRawInjectionDespiteWrapping = false; // 依賴項檢查和自動裝配時忽略的依賴項類型 private final Set<Class<?>> ignoredDependencyTypes = new HashSet<>(); // 依賴項檢查和自動裝配時忽略的依賴項接口 private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<>(); // 當前正在建立的bean private final NamedThreadLocal<String> currentlyCreatedBean = new NamedThreadLocal<>("Currently created bean"); // beanName和FactoryBean的映射 private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>(); // 類和候選方法映射 private final ConcurrentMap<Class<?>, Method[]> factoryMethodCandidateCache = new ConcurrentHashMap<>(); // 類和PropertyDescriptor的映射 private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache = new ConcurrentHashMap<>();
構造函數,忽略BeanNameAware、BeanFactoryAware、BeanClassLoaderAware的依賴。數組
public AbstractAutowireCapableBeanFactory() { super(); ignoreDependencyInterface(BeanNameAware.class); ignoreDependencyInterface(BeanFactoryAware.class); ignoreDependencyInterface(BeanClassLoaderAware.class); } public AbstractAutowireCapableBeanFactory(@Nullable BeanFactory parentBeanFactory) { this(); setParentBeanFactory(parentBeanFactory); }
生成策略的設值與獲取緩存
public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) { this.instantiationStrategy = instantiationStrategy; } protected InstantiationStrategy getInstantiationStrategy() { return this.instantiationStrategy; }
解析策略的方法參數的設值與獲取app
public void setParameterNameDiscoverer(@Nullable ParameterNameDiscoverer parameterNameDiscoverer) { this.parameterNameDiscoverer = parameterNameDiscoverer; } protected ParameterNameDiscoverer getParameterNameDiscoverer() { return this.parameterNameDiscoverer; }
嘗試解析循環引用ide
public void setAllowCircularReferences(boolean allowCircularReferences) { this.allowCircularReferences = allowCircularReferences; }
在循環引用的狀況下,是否須要注入一個原始的bean實例函數
public void setAllowRawInjectionDespiteWrapping(boolean allowRawInjectionDespiteWrapping) { this.allowRawInjectionDespiteWrapping = allowRawInjectionDespiteWrapping; }
依賴項檢查和自動裝配時忽略的依賴項類型post
public void ignoreDependencyType(Class<?> type) { this.ignoredDependencyTypes.add(type); }
依賴項檢查和自動裝配時忽略的依賴項接口。這個做用是這樣的:好比A中有屬性B,正常A初始化的時候,若是B沒有初始化,這個時候,會初始化B。好比構造函數設置了幾個Aware接口,就不會在做爲屬性B的時候初始化。this
public void ignoreDependencyInterface(Class<?> ifc) { this.ignoredDependencyInterfaces.add(ifc); }
除了複製父類的幾種配置,好包括了instantiationStrategy、allowCircularReferences、ignoredDependencyTypes、ignoredDependencyInterfacesspa
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { super.copyConfigurationFrom(otherFactory); if (otherFactory instanceof AbstractAutowireCapableBeanFactory) { AbstractAutowireCapableBeanFactory otherAutowireFactory = (AbstractAutowireCapableBeanFactory) otherFactory; this.instantiationStrategy = otherAutowireFactory.instantiationStrategy; this.allowCircularReferences = otherAutowireFactory.allowCircularReferences; this.ignoredDependencyTypes.addAll(otherAutowireFactory.ignoredDependencyTypes); this.ignoredDependencyInterfaces.addAll(otherAutowireFactory.ignoredDependencyInterfaces); } }
建立beanprototype
public <T> T createBean(Class<T> beanClass) throws BeansException { // Use prototype bean definition, to avoid registering bean as dependent bean. // 封裝到BeanDefinition RootBeanDefinition bd = new RootBeanDefinition(beanClass); bd.setScope(SCOPE_PROTOTYPE); // 是否容許緩存 bd.allowCaching = ClassUtils.isCacheSafe(beanClass, getBeanClassLoader()); return (T) createBean(beanClass.getName(), bd, null); } protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { 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 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { // 不爲空,且mbd沒有類信息,從新設值 mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try { // 以前的lookup註解或者<lookup-method /> 標籤就是這裏實現的,還有<replaced-method /> mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. // 前置處理器是否返回bean Object bean = resolveBeforeInstantiation(beanName, mbdToUse); if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } try { // 建立bean Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isTraceEnabled()) { logger.trace("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { // A previously detected exception with proper bean creation context already, // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry. throw ex; } catch (Throwable ex) { throw new BeanCreationException( mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); } } protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException { // Instantiate the bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { // 返回空,說明不是FactoryBean,根據實際的策略生成BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args); } // 獲取bean的實例 final Object bean = instanceWrapper.getWrappedInstance(); // 獲取bean的類型 Class<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType; } // Allow post-processors to modify the merged bean definition. // MergedBeanDefinitionPostProcessor後置處理器修改合併bean的定義 synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } // 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"); } // 此時還沒初始化完成,只是構造了,先把ObjectFactory加入到singletonFactories addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // Initialize the bean instance. Object exposedObject = bean; try { // 實例化後,對bean各個屬性進行賦值 populateBean(beanName, mbd, instanceWrapper); // 賦值後,調用init方法,InitializingBean這些 exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); // 循環依賴的狀況 if (earlySingletonReference != null) { // 判斷在initializeBean方法裏有沒有被改變,被改變返回改變後的,沒有改變,從緩存中取 if (exposedObject == bean) { exposedObject = earlySingletonReference; } // 被改變了,檢查依賴 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { // 返回false說明依賴還沒實例化好 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } // actualDependentBeans不爲空,說明依賴還沒實例化好,拋異常 if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } } // Register bean as disposable. try { // 根據scope註冊DisposableBean registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }
給bean的屬性賦值
public void autowireBean(Object existingBean) { // Use non-singleton bean definition, to avoid registering bean as dependent bean. RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean)); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader()); BeanWrapper bw = new BeanWrapperImpl(existingBean); // 初始化BeanWrapper initBeanWrapper(bw); // 給bean的屬性賦值 populateBean(bd.getBeanClass().getName(), bd, bw); }
public Object configureBean(Object existingBean, String beanName) throws BeansException { // 若是已經建立了,bean的定義要清除 markBeanAsCreated(beanName); // 從新設置bean的定義 BeanDefinition mbd = getMergedBeanDefinition(beanName); RootBeanDefinition bd = null; if (mbd instanceof RootBeanDefinition) { RootBeanDefinition rbd = (RootBeanDefinition) mbd; bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition()); } if (bd == null) { bd = new RootBeanDefinition(mbd); } if (!bd.isPrototype()) { bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader()); } BeanWrapper bw = new BeanWrapperImpl(existingBean); // 初始化BeanWrapper initBeanWrapper(bw); // 給bean的屬性賦值 populateBean(beanName, bd, bw); // 調用init方法,InitializingBean這些 return initializeBean(beanName, existingBean, bd); }
使用指定的自動裝配策略實例化給定類的新bean實例
public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException { // Use non-singleton bean definition, to avoid registering bean as dependent bean. final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); // 若是是構造器注入 if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) { return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance(); } else { Object bean; final BeanFactory parent = this; if (System.getSecurityManager() != null) { bean = AccessController.doPrivileged((PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(bd, null, parent), getAccessControlContext()); } else { // 生成bean bean = getInstantiationStrategy().instantiate(bd, null, parent); } // 給bean的屬性賦值 populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean)); return bean; } }
根據名稱或類型自動裝配給定bean實例的bean屬性。
public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException { if (autowireMode == AUTOWIRE_CONSTRUCTOR) { throw new IllegalArgumentException("AUTOWIRE_CONSTRUCTOR not supported for existing bean instance"); } // Use non-singleton bean definition, to avoid registering bean as dependent bean. RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean), autowireMode, dependencyCheck); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); BeanWrapper bw = new BeanWrapperImpl(existingBean); initBeanWrapper(bw); // 給bean的屬性賦值 populateBean(bd.getBeanClass().getName(), bd, bw); }
將具備給定名稱的bean定義的屬性值應用於給定的bean實例
public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException { markBeanAsCreated(beanName); BeanDefinition bd = getMergedBeanDefinition(beanName); BeanWrapper bw = new BeanWrapperImpl(existingBean); initBeanWrapper(bw); applyPropertyValues(beanName, bd, bw, bd.getPropertyValues()); }
public Object initializeBean(Object existingBean, String beanName) { return initializeBean(beanName, existingBean, null); } 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 { // 調用BeanNameAware、BeanClassLoaderAware、BeanFactoryAware invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { // 前置處理器 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()) { // 後置處理器 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }
前置處理器
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; // 獲取BeanPostProcessor處理 for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessBeforeInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }
後置處理器
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; // 獲取BeanPostProcessor處理 for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }
銷燬bean
public void destroyBean(Object existingBean) { new DisposableBeanAdapter(existingBean, getBeanPostProcessors(), getAccessControlContext()).destroy(); }
解析給定bean名稱的bean實例,爲目標工廠方法提供依賴描述符。
public Object resolveBeanByName(String name, DependencyDescriptor descriptor) { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { // 獲取bean return getBean(name, descriptor.getDependencyType()); } finally { // 爲目標工廠方法提供依賴描述符 ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } }
根據工廠中定義的bean解析指定的依賴項。
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException { return resolveDependency(descriptor, requestingBeanName, null, null); }
預測bean類型
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { // 肯定給定bean定義的目標類型。 Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch); // Apply SmartInstantiationAwareBeanPostProcessors to predict the // eventual type after a before-instantiation shortcut. // 經過SmartInstantiationAwareBeanPostProcessors獲取實際類型 if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; Class<?> predicted = ibp.predictBeanType(targetType, beanName); if (predicted != null && (typesToMatch.length != 1 || FactoryBean.class != typesToMatch[0] || FactoryBean.class.isAssignableFrom(predicted))) { return predicted; } } } } return targetType; }
肯定給定bean定義的目標類型。
protected Class<?> determineTargetType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { Class<?> targetType = mbd.getTargetType(); if (targetType == null) { targetType = (mbd.getFactoryMethodName() != null ? getTypeForFactoryMethod(beanName, mbd, typesToMatch) : resolveBeanClass(mbd, beanName, typesToMatch)); if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) { mbd.resolvedTargetType = targetType; } } return targetType; }
肯定基於工廠方法的給定bean定義的目標類型。只有在沒有爲目標bean註冊單例實例時才調用
protected Class<?> getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { // 獲取目標方法返回類型 ResolvableType cachedReturnType = mbd.factoryMethodReturnType; if (cachedReturnType != null) { return cachedReturnType.resolve(); } Class<?> factoryClass; boolean isStatic = true; String factoryBeanName = mbd.getFactoryBeanName(); if (factoryBeanName != null) { // factoryBean的狀況 if (factoryBeanName.equals(beanName)) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "factory-bean reference points back to the same bean definition"); } // Check declared factory method return type on factory class. // 獲取指定beanName的類型 factoryClass = getType(factoryBeanName); isStatic = false; } else { // Check declared factory method return type on bean class. // 解析類名 factoryClass = resolveBeanClass(mbd, beanName, typesToMatch); } if (factoryClass == null) { return null; } factoryClass = ClassUtils.getUserClass(factoryClass); // If all factory methods have the same return type, return that type. // Can't clearly figure out exact method due to type converting / autowiring! Class<?> commonType = null; Method uniqueCandidate = null; // 獲取構造函數的參數個數 int minNrOfArgs = (mbd.hasConstructorArgumentValues() ? mbd.getConstructorArgumentValues().getArgumentCount() : 0); // 方法候選 Method[] candidates = this.factoryMethodCandidateCache.computeIfAbsent( factoryClass, ReflectionUtils::getUniqueDeclaredMethods); // 有多個的狀況,須要遍歷查找 for (Method candidate : candidates) { if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate) && candidate.getParameterCount() >= minNrOfArgs) { // Declared type variables to inspect? if (candidate.getTypeParameters().length > 0) { try { // Fully resolve parameter names and argument values. // 解析參數名和參數值 Class<?>[] paramTypes = candidate.getParameterTypes(); String[] paramNames = null; ParameterNameDiscoverer pnd = getParameterNameDiscoverer(); if (pnd != null) { paramNames = pnd.getParameterNames(candidate); } ConstructorArgumentValues cav = mbd.getConstructorArgumentValues(); Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length); Object[] args = new Object[paramTypes.length]; for (int i = 0; i < args.length; i++) { ConstructorArgumentValues.ValueHolder valueHolder = cav.getArgumentValue( i, paramTypes[i], (paramNames != null ? paramNames[i] : null), usedValueHolders); if (valueHolder == null) { valueHolder = cav.getGenericArgumentValue(null, null, usedValueHolders); } if (valueHolder != null) { args[i] = valueHolder.getValue(); usedValueHolders.add(valueHolder); } } Class<?> returnType = AutowireUtils.resolveReturnTypeForFactoryMethod( candidate, args, getBeanClassLoader()); uniqueCandidate = (commonType == null && returnType == candidate.getReturnType() ? candidate : null); commonType = ClassUtils.determineCommonAncestor(returnType, commonType); if (commonType == null) { // Ambiguous return types found: return null to indicate "not determinable". return null; } } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to resolve generic return type for factory method: " + ex); } } } else { uniqueCandidate = (commonType == null ? candidate : null); commonType = ClassUtils.determineCommonAncestor(candidate.getReturnType(), commonType); if (commonType == null) { // Ambiguous return types found: return null to indicate "not determinable". return null; } } } } mbd.factoryMethodToIntrospect = uniqueCandidate; if (commonType == null) { return null; } // Common return type found: all factory methods return same type. For a non-parameterized // unique candidate, cache the full type declaration context of the target factory method. cachedReturnType = (uniqueCandidate != null ? ResolvableType.forMethodReturnType(uniqueCandidate) : ResolvableType.forClass(commonType)); mbd.factoryMethodReturnType = cachedReturnType; return cachedReturnType.resolve(); }
獲取FactoryBean的類型
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) { if (mbd.getInstanceSupplier() != null) { ResolvableType targetType = mbd.targetType; if (targetType != null) { Class<?> result = targetType.as(FactoryBean.class).getGeneric().resolve(); if (result != null) { // 若是是FactoryBean就返回 return result; } } if (mbd.hasBeanClass()) { Class<?> result = GenericTypeResolver.resolveTypeArgument(mbd.getBeanClass(), FactoryBean.class); if (result != null) { return result; } } } String factoryBeanName = mbd.getFactoryBeanName(); String factoryMethodName = mbd.getFactoryMethodName(); if (factoryBeanName != null) { if (factoryMethodName != null) { // Try to obtain the FactoryBean's object type from its factory method declaration // without instantiating the containing bean at all. // 從聲明中獲取FactoryBean的對象類型 BeanDefinition fbDef = getBeanDefinition(factoryBeanName); if (fbDef instanceof AbstractBeanDefinition) { AbstractBeanDefinition afbDef = (AbstractBeanDefinition) fbDef; if (afbDef.hasBeanClass()) { Class<?> result = getTypeForFactoryBeanFromMethod(afbDef.getBeanClass(), factoryMethodName); if (result != null) { return result; } } } } // If not resolvable above and the referenced factory bean doesn't exist yet, // exit here - we don't want to force the creation of another bean just to // obtain a FactoryBean's object type... // 定義中沒有,且沒有建立過返回空 if (!isBeanEligibleForMetadataCaching(factoryBeanName)) { return null; } } // Let's obtain a shortcut instance for an early getObjectType() call... // 若是是單例的,經過單例類型的方法獲取FactoryBean,若是是多例的,經過多例類型的方法獲取FactoryBean FactoryBean<?> fb = (mbd.isSingleton() ? getSingletonFactoryBeanForTypeCheck(beanName, mbd) : getNonSingletonFactoryBeanForTypeCheck(beanName, mbd)); if (fb != null) { // Try to obtain the FactoryBean's object type from this early stage of the instance. // 已經有FactoryBean實例,調用他的getObjectType方法 Class<?> result = getTypeForFactoryBean(fb); if (result != null) { return result; } else { // No type found for shortcut FactoryBean instance: // fall back to full creation of the FactoryBean instance. // 沒有獲取到經過beanName和定義獲取FactoryBean的類型 return super.getTypeForFactoryBean(beanName, mbd); } } if (factoryBeanName == null && mbd.hasBeanClass()) { // No early bean instantiation possible: determine FactoryBean's type from // static factory method signature or from class inheritance hierarchy... if (factoryMethodName != null) { return getTypeForFactoryBeanFromMethod(mbd.getBeanClass(), factoryMethodName); } else { return GenericTypeResolver.resolveTypeArgument(mbd.getBeanClass(), FactoryBean.class); } } return null; }
查詢FactoryBean的通用參數元數據(若是存在的話)以肯定對象類型
private Class<?> getTypeForFactoryBeanFromMethod(Class<?> beanClass, final String factoryMethodName) { /** * Holder used to keep a reference to a {@code Class} value. */ class Holder { @Nullable Class<?> value = null; } final Holder objectType = new Holder(); // CGLIB subclass methods hide generic parameters; look at the original user class. Class<?> fbClass = ClassUtils.getUserClass(beanClass); // Find the given factory method, taking into account that in the case of // @Bean methods, there may be parameters present. ReflectionUtils.doWithMethods(fbClass, method -> { if (method.getName().equals(factoryMethodName) && FactoryBean.class.isAssignableFrom(method.getReturnType())) { Class<?> currentType = GenericTypeResolver.resolveReturnTypeArgument(method, FactoryBean.class); if (currentType != null) { objectType.value = ClassUtils.determineCommonAncestor(currentType, objectType.value); } } }); return (objectType.value != null && Object.class != objectType.value ? objectType.value : null); }
獲取指定bean的早期訪問引用,一般用於解析循環引用。
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) { Object exposedObject = bean; if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName); } } } return exposedObject; }
單例的話,獲取FactoryBean
private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) { // 加鎖 synchronized (getSingletonMutex()) { // 是否已經實例化 BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName); if (bw != null) { // 實例化直接返回 return (FactoryBean<?>) bw.getWrappedInstance(); } // factoryBeanInstanceCache沒有,看看是否已經建立 Object beanInstance = getSingleton(beanName, false); // 建立好的單例是FactoryBean,直接返回 if (beanInstance instanceof FactoryBean) { return (FactoryBean<?>) beanInstance; } // 建立好的單例不是FactoryBean,或者已經建立或者正在建立,返回空 if (isSingletonCurrentlyInCreation(beanName) || (mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) { return null; } // Object instance; try { // Mark this bean as currently in creation, even if just partially. // 建立前檢查 beforeSingletonCreation(beanName); // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. // 看看代理能不能返回一個實例 instance = resolveBeforeInstantiation(beanName, mbd); if (instance == null) { // 代理沒返回,就建立一個 bw = createBeanInstance(beanName, mbd, null); instance = bw.getWrappedInstance(); } } catch (UnsatisfiedDependencyException ex) { // Don't swallow, probably misconfiguration... throw ex; } catch (BeanCreationException ex) { // Instantiation failure, maybe too early... if (logger.isDebugEnabled()) { logger.debug("Bean creation exception on singleton FactoryBean type check: " + ex); } onSuppressedException(ex); return null; } finally { // Finished partial creation of this bean. // 建立後檢查 afterSingletonCreation(beanName); } // 獲取到的實例轉換爲FactoryBean FactoryBean<?> fb = getFactoryBean(beanName, instance); if (bw != null) { // 放入緩存 this.factoryBeanInstanceCache.put(beanName, bw); } return fb; } }
不是單例的話,獲取FactoryBean,比單例少的步驟是factoryBeanInstanceCache緩衝的操做
private FactoryBean<?> getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) { // 當前線程有在建立 if (isPrototypeCurrentlyInCreation(beanName)) { return null; } Object instance; try { // Mark this bean as currently in creation, even if just partially. // 標記正在建立 beforePrototypeCreation(beanName); // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. // 看看代理能不能返回一個實例 instance = resolveBeforeInstantiation(beanName, mbd); if (instance == null) { BeanWrapper bw = createBeanInstance(beanName, mbd, null); instance = bw.getWrappedInstance(); } } catch (UnsatisfiedDependencyException ex) { // Don't swallow, probably misconfiguration... throw ex; } catch (BeanCreationException ex) { // Instantiation failure, maybe too early... if (logger.isDebugEnabled()) { logger.debug("Bean creation exception on non-singleton FactoryBean type check: " + ex); } onSuppressedException(ex); return null; } finally { // Finished partial creation of this bean. // 標記建立結束 afterPrototypeCreation(beanName); } // 直接轉換爲FactoryBean return getFactoryBean(beanName, instance); }
MergedBeanDefinitionPostProcessor的合併定義
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof MergedBeanDefinitionPostProcessor) { MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp; bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName); } } }
應用實例化先後處理程序,解決指定bean是否有實例化前快捷方式
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { Object bean = null; // 沒有明確標明false 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) { // 嘗試初始化 bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); if (bean != null) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } mbd.beforeInstantiationResolved = (bean != null); } return bean; }
嘗試初始化
@Nullable protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName); if (result != null) { return result; } } } return null; }
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { // Make sure bean class is actually resolved at this point. // 解析beanClass Class<?> beanClass = resolveBeanClass(mbd, beanName); // 判斷是否有類的訪問權限 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } // 是否有其餘回調 Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); if (instanceSupplier != null) { return obtainFromSupplier(instanceSupplier, beanName); } // 是否有工廠方法回調 if (mbd.getFactoryMethodName() != null) { return instantiateUsingFactoryMethod(beanName, mbd, args); } // Shortcut when re-creating the same bean... // 是否解析過 boolean resolved = false; // 爲false說明無參,true有參 boolean autowireNecessary = false; if (args == null) { synchronized (mbd.constructorArgumentLock) { // 若是構造方法解析過 if (mbd.resolvedConstructorOrFactoryMethod != null) { resolved = true; autowireNecessary = mbd.constructorArgumentsResolved; } } } // 解析過了,根據是否有參數選擇無參構造仍是有參構造 if (resolved) { if (autowireNecessary) { // 有參構造 return autowireConstructor(beanName, mbd, null, null); } else { // 無參構造 return instantiateBean(beanName, mbd); } } // Candidate constructors for autowiring? // 根據bean的定義解析參數 Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { // 構造器注入 return autowireConstructor(beanName, mbd, ctors, args); } // Preferred constructors for default construction? ctors = mbd.getPreferredConstructors(); if (ctors != null) { // 構造器注入 return autowireConstructor(beanName, mbd, ctors, null); } // No special handling: simply use no-arg constructor. // 無參構造 return instantiateBean(beanName, mbd); }
從Supplier獲取bean
protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) { Object instance; // 獲取原先建立的beanName String outerBean = this.currentlyCreatedBean.get(); // 用當前的替換 this.currentlyCreatedBean.set(beanName); try { // 調用Supplier的方法 instance = instanceSupplier.get(); } finally { // 原先的bean存在,設置爲原先的 if (outerBean != null) { this.currentlyCreatedBean.set(outerBean); } // 原先的不存在,就移除,反正本來也爲空 else { this.currentlyCreatedBean.remove(); } } // 沒有建立對象,默認爲NullBean if (instance == null) { instance = new NullBean(); } // 初始化BeanWrapper並返回 BeanWrapper bw = new BeanWrapperImpl(instance); initBeanWrapper(bw); return bw; }
protected Object getObjectForBeanInstance( Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) { // 註冊當前建立的bean和給定beanName的依賴 String currentlyCreatedBean = this.currentlyCreatedBean.get(); if (currentlyCreatedBean != null) { registerDependentBean(beanName, currentlyCreatedBean); } // 返回一個bean return super.getObjectForBeanInstance(beanInstance, name, beanName, mbd); }
肯定bean的構造函數
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName) throws BeansException { if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { // 從SmartInstantiationAwareBeanPostProcessor判斷 SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName); if (ctors != null) { return ctors; } } } } return null; }
無參構造bean
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) { try { Object beanInstance; final BeanFactory parent = this; if (System.getSecurityManager() != null) { beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, parent), getAccessControlContext()); } else { // 建立一個bean beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent); } // 初始化BeanWrapper並返回 BeanWrapper bw = new BeanWrapperImpl(beanInstance); initBeanWrapper(bw); return bw; } catch (Throwable ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); } }
使用FactoryMethod實例化一個bean
protected BeanWrapper instantiateUsingFactoryMethod( String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) { return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs); }
實例化後封裝成BeanWrapper
protected BeanWrapper autowireConstructor( String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) { return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs); }
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { if (bw == null) { // 若是BeanWrapper爲空,可是有屬性值,就跑異常 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. // 看看InstantiationAwareBeanPostProcessors是否有注入值,若是有注入,就不繼續注入,直接返回 boolean continueWithPropertyPopulation = true; if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { continueWithPropertyPopulation = false; break; } } } } if (!continueWithPropertyPopulation) { return; } PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) { // 拷貝配置信息 MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. // 根據名稱注入 if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. // 根據類型注入 if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } // r容器是否有InstantiationAwareBeanPostProcessors 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); } }
根據名稱注入
protected void autowireByName( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { // 獲取可set的屬性,且這個屬性不是簡單的屬性,好比基本類型、包裝類這些 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { // 是否有這個bean if (containsBean(propertyName)) { // 有的話獲取 Object bean = getBean(propertyName); // 添加到pvs pvs.add(propertyName, bean); // 註冊依賴關係 registerDependentBean(propertyName, beanName); if (logger.isTraceEnabled()) { logger.trace("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { if (logger.isTraceEnabled()) { logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } } }
根據類型注入
protected void autowireByType( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { // 類型轉換器獲取 TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } Set<String> autowiredBeanNames = new LinkedHashSet<>(4); // 獲取可set的屬性,且這個屬性不是簡單的屬性,好比基本類型、包裝類這些 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { try { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); // Don't try autowiring by type for type Object: never makes sense, // even if it technically is a unsatisfied, non-simple property. // 若是是Object,就無論了 if (Object.class != pd.getPropertyType()) { // 獲取寫參數 MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); // Do not allow eager init for type matching in case of a prioritized post-processor. // 是否當即初始化 boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance()); // 依賴描述 DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager); // 解析依賴 Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); if (autowiredArgument != null) { pvs.add(propertyName, autowiredArgument); } for (String autowiredBeanName : autowiredBeanNames) { // 註冊依賴 registerDependentBean(autowiredBeanName, beanName); if (logger.isTraceEnabled()) { logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + autowiredBeanName + "'"); } } autowiredBeanNames.clear(); } } catch (BeansException ex) { throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); } } }
返回一個不是簡單的bean屬性數組不包括基本類型或字符串等簡單屬性。
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) { Set<String> result = new TreeSet<>(); PropertyValues pvs = mbd.getPropertyValues(); PropertyDescriptor[] pds = bw.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) && !BeanUtils.isSimpleProperty(pd.getPropertyType())) { result.add(pd.getName()); } } return StringUtils.toStringArray(result); }
過濾出須要依賴檢查的屬性
protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw, boolean cache) { PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass()); if (filtered == null) { filtered = filterPropertyDescriptorsForDependencyCheck(bw); // 緩存 if (cache) { PropertyDescriptor[] existing = this.filteredPropertyDescriptorsCache.putIfAbsent(bw.getWrappedClass(), filtered); if (existing != null) { filtered = existing; } } } return filtered; } protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) { List<PropertyDescriptor> pds = new ArrayList<>(Arrays.asList(bw.getPropertyDescriptors())); pds.removeIf(this::isExcludedFromDependencyCheck); return pds.toArray(new PropertyDescriptor[0]); }
指定的bean屬性是否被排除在依賴項檢查以外。
protected boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) { return (AutowireUtils.isExcludedFromDependencyCheck(pd) || this.ignoredDependencyTypes.contains(pd.getPropertyType()) || AutowireUtils.isSetterDefinedInInterface(pd, this.ignoredDependencyInterfaces)); }
檢查依賴項是不是公開的
protected void checkDependencies( String beanName, AbstractBeanDefinition mbd, PropertyDescriptor[] pds, @Nullable PropertyValues pvs) throws UnsatisfiedDependencyException { int dependencyCheck = mbd.getDependencyCheck(); for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() != null && (pvs == null || !pvs.contains(pd.getName()))) { boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType()); boolean unsatisfied = (dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_ALL) || (isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_SIMPLE) || (!isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_OBJECTS); if (unsatisfied) { throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(), "Set this property value or disable dependency checking for this bean."); } } } }
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { // 爲空直接返回 if (pvs.isEmpty()) { return; } if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) { ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); } MutablePropertyValues mpvs = null; List<PropertyValue> original; if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; if (mpvs.isConverted()) { // Shortcut: use the pre-converted values as-is. try { // 已完成,直接返回 bw.setPropertyValues(mpvs); return; } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } original = mpvs.getPropertyValueList(); } else { original = Arrays.asList(pvs.getPropertyValues()); } TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } // bean定義解析器 BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); // Create a deep copy, resolving any references for values. List<PropertyValue> deepCopy = new ArrayList<>(original.size()); boolean resolveNecessary = false; // 對original的深度複製,已解析的直接加到deepCopy,沒解析的先解析,再加入到deepCopy for (PropertyValue pv : original) { // 已解析 if (pv.isConverted()) { deepCopy.add(pv); } else { String propertyName = pv.getName(); Object originalValue = pv.getValue(); // 解析值 Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue); Object convertedValue = resolvedValue; boolean convertible = bw.isWritableProperty(propertyName) && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName); // 是否須要轉換 if (convertible) { // 嘗試轉換 convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter); } // Possibly store converted value in merged bean definition, // in order to avoid re-conversion for every created bean instance. // 解析值和原值同樣 if (resolvedValue == originalValue) { // 避免重複轉換 if (convertible) { pv.setConvertedValue(convertedValue); } deepCopy.add(pv); } else if (convertible && originalValue instanceof TypedStringValue && !((TypedStringValue) originalValue).isDynamic() && !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) { pv.setConvertedValue(convertedValue); deepCopy.add(pv); } else { resolveNecessary = true; deepCopy.add(new PropertyValue(pv, convertedValue)); } } } if (mpvs != null && !resolveNecessary) { mpvs.setConverted(); } // Set our (possibly massaged) deep copy. try { // 設值 bw.setPropertyValues(new MutablePropertyValues(deepCopy)); } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } }
轉換值initializeBean
private Object convertForProperty( @Nullable Object value, String propertyName, BeanWrapper bw, TypeConverter converter) { if (converter instanceof BeanWrapperImpl) { return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName); } else { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam); } }
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd) throws Throwable { boolean isInitializingBean = (bean instanceof InitializingBean); // 若是是InitializingBean而且有afterPropertiesSet,調用afterPropertiesSet方法 if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { if (logger.isTraceEnabled()) { logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); } if (System.getSecurityManager() != null) { try { AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> { ((InitializingBean) bean).afterPropertiesSet(); return null; }, getAccessControlContext()); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { ((InitializingBean) bean).afterPropertiesSet(); } } // 若是是InitializingBean,但沒有afterPropertiesSet,調用自定義的方法 if (mbd != null && bean.getClass() != NullBean.class) { String initMethodName = mbd.getInitMethodName(); if (StringUtils.hasLength(initMethodName) && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { invokeCustomInitMethod(beanName, bean, mbd); } } }
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { // 獲取初始化方法名稱 String initMethodName = mbd.getInitMethodName(); Assert.state(initMethodName != null, "No init method set"); // 獲取初始化方法 final Method initMethod = (mbd.isNonPublicAccessAllowed() ? BeanUtils.findMethod(bean.getClass(), initMethodName) : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName)); if (initMethod == null) { if (mbd.isEnforceInitMethod()) { throw new BeanDefinitionValidationException("Could not find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'"); } else { if (logger.isTraceEnabled()) { logger.trace("No default init method named '" + initMethodName + "' found on bean with name '" + beanName + "'"); } // Ignore non-existent default lifecycle methods. return; } } if (logger.isTraceEnabled()) { logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'"); } if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { ReflectionUtils.makeAccessible(initMethod); return null; }); try { AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> initMethod.invoke(bean), getAccessControlContext()); } catch (PrivilegedActionException pae) { InvocationTargetException ex = (InvocationTargetException) pae.getException(); throw ex.getTargetException(); } } else { try { // 給權限 ReflectionUtils.makeAccessible(initMethod); // 反射 initMethod.invoke(bean); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } }
調用後置處理器
protected Object postProcessObjectFromFactoryBean(Object object, String beanName) { return applyBeanPostProcessorsAfterInitialization(object, beanName); }
移除單例,這邊額外多了factoryBeanInstanceCache緩存
protected void removeSingleton(String beanName) { synchronized (getSingletonMutex()) { super.removeSingleton(beanName); this.factoryBeanInstanceCache.remove(beanName); } }
清空單例,這邊額外多了factoryBeanInstanceCache緩存
protected void clearSingletonCache() { synchronized (getSingletonMutex()) { super.clearSingletonCache(); this.factoryBeanInstanceCache.clear(); } }
獲取logger
Log getLogger() { return logger; }