1. 程式人生 > >Spring中Bean容器DefaultListableBeanFactory核心實現原始碼分析

Spring中Bean容器DefaultListableBeanFactory核心實現原始碼分析

文章目錄

DefaultListableBeanFactory的繼承結構

 DefaultListableBeanFactory是介面ConfigurableListableBeanFactory和BeanDefinitionRegistry的預設實現,可以理解為Spring容器中預設的物件工廠的實現,是一個比較全面的物件工廠。工廠中的Bean都是基於元資料定義的 bean 和通過post-processors擴充套件的bean。它的典型作用就是註冊所有的bean通過讀取bean的配置檔案,這樣就可以通過bean的命名方便快速訪問bean,通過本地快取表。DefaultListableBeanFactory的繼承結構如下圖:DefaultListableBeanFactory的繼承結構
 下面逐個看看上層介面和跟類都提供了哪些方式和實現。

BeanFactory

BeanFactory定義的介面如下:

 /*Spring物件工廠的最頂層介面,最基礎的物件容器檢視*/
public interface BeanFactory {

	 /*區分FactoryBean例項和FactoryBean建立的例項*/
	String FACTORY_BEAN_PREFIX = "&";

	  /*獲取一個物件例項,單例物件返回都是物件的引用*/
	Object getBean(String name) throws BeansException;

	 /*獲取一個物件例項,requiredType是一個介面,或者例項類的父類*/
	<T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException;
	
    /*獲取一個物件例項,args是建立例項具體引數*/
	Object getBean(String name, Object... args) throws BeansException;
	
   /*獲取一個物件例項,requiredType是一個介面,或者例項類的父類*/
	<T> T getBean(Class<T> requiredType) throws BeansException;

	<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
	
	/*判斷物件工廠中是否有指定名稱name的物件*/
	boolean containsBean(String name);

	/*判斷物件工廠中名稱name的物件是否是單例的*/
	boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
   
   /*判斷物件工廠中名稱name的物件是否是prototype型別的*/
	boolean isPrototype(String name) throws NoSuchBeanDefinitionException;

   /*判斷物件工廠中名稱name的例項是否typeToMatch型別匹配*/
	boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;

	boolean isTypeMatch(String name, @Nullable Class<?> typeToMatch) throws NoSuchBeanDefinitionException;

 	/*判斷物件工廠中名稱name例項的型別*/
	@Nullable
	Class<?> getType(String name) throws NoSuchBeanDefinitionException;
 
   /*判斷物件工廠中名稱name的別稱*/
    String[] getAliases(String name);
}
AliasRegistry

 AliasRegistry是管理別稱的通用介面,作為BeanDefinitionRegistry的頂層介面

public interface AliasRegistry {
	void registerAlias(String name, String alias);
	void removeAlias(String alias);
	boolean isAlias(String name);
	String[] getAliases(String name);
}
BeanDefinitionRegistry

 BeanDefinition的註冊介面定義如下:

public interface BeanDefinitionRegistry extends AliasRegistry {
	
	void registerBeanDefinition(String beanName, BeanDefinition beanDefinition);
	void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
	BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
	boolean containsBeanDefinition(String beanName);
	String[] getBeanDefinitionNames();
	int getBeanDefinitionCount();
	boolean isBeanNameInUse(String beanName);
}
SimpleAliasRegistry

SimpleAliasRegistry是AliasRegistry的簡單實現

public class SimpleAliasRegistry implements AliasRegistry {

	/* 規範名和別稱的對映 */
	private final Map<String, String> aliasMap = new ConcurrentHashMap<>(16);

    /* 註冊別稱 */
	@Override
	public void registerAlias(String name, String alias) {
		Assert.hasText(name, "'name' must not be empty");
		Assert.hasText(alias, "'alias' must not be empty");
		synchronized (this.aliasMap) {
			if (alias.equals(name)) {
				this.aliasMap.remove(alias);
				if (logger.isDebugEnabled()) {
					logger.debug("Alias definition '" + alias + "' ignored since it points to same name");
				}
			}
			else {
				String registeredName = this.aliasMap.get(alias);
				if (registeredName != null) {
					if (registeredName.equals(name)) {
						// An existing alias - no need to re-register
						return;
					}
					if (!allowAliasOverriding()) {
						throw new IllegalStateException("Cannot define alias '" + alias + "' for name '" +
								name + "': It is already registered for name '" + registeredName + "'.");
					}
					if (logger.isInfoEnabled()) {
						logger.info("Overriding alias '" + alias + "' definition for registered name '" +
								registeredName + "' with new target name '" + name + "'");
					}
				}
				
				/*檢測別稱中是否有環*/
				checkForAliasCircle(name, alias);
				
				/*放入快取*/
				this.aliasMap.put(alias, name);
				if (logger.isDebugEnabled()) {
					logger.debug("Alias definition '" + alias + "' registered for name '" + name + "'");
				}
			}
		}
	}
	
	protected boolean allowAliasOverriding() {
		return true;
	}

   /*遞迴判斷是否有名稱為name的別稱alias*/
	public boolean hasAlias(String name, String alias) {
		for (Map.Entry<String, String> entry : this.aliasMap.entrySet()) {
			String registeredName = entry.getValue();
			if (registeredName.equals(name)) {
				String registeredAlias = entry.getKey();
				return (registeredAlias.equals(alias) || hasAlias(registeredAlias, alias));
			}
		}
		return false;
	}

	@Override
	public void removeAlias(String alias) {
		synchronized (this.aliasMap) {
			String name = this.aliasMap.remove(alias);
			if (name == null) {
				throw new IllegalStateException("No alias '" + alias + "' registered");
			}
		}
	}

	@Override
	public boolean isAlias(String name) {
		return this.aliasMap.containsKey(name);
	}

	@Override
	public String[] getAliases(String name) {
		List<String> result = new ArrayList<>();
		synchronized (this.aliasMap) {
			retrieveAliases(name, result);
		}
		return StringUtils.toStringArray(result);
	}

	private void retrieveAliases(String name, List<String> result) {
		this.aliasMap.forEach((alias, registeredName) -> {
			if (registeredName.equals(name)) {
				result.add(alias);
				retrieveAliases(alias, result);
			}
		});
	}
	
   /*解析別稱*/
	public void resolveAliases(StringValueResolver valueResolver) {
		Assert.notNull(valueResolver, "StringValueResolver must not be null");
		synchronized (this.aliasMap) {
			Map<String, String> aliasCopy = new HashMap<>(this.aliasMap);
			aliasCopy.forEach((alias, registeredName) -> {
				String resolvedAlias = valueResolver.resolveStringValue(alias);
				String resolvedName = valueResolver.resolveStringValue(registeredName);
				if (resolvedAlias == null || resolvedName == null || resolvedAlias.equals(resolvedName)) {
					this.aliasMap.remove(alias);
				}
				else if (!resolvedAlias.equals(alias)) {
					String existingName = this.aliasMap.get(resolvedAlias);
					if (existingName != null) {
						if (existingName.equals(resolvedName)) {
							// Pointing to existing alias - just remove placeholder
							this.aliasMap.remove(alias);
							return;
						}
						throw new IllegalStateException(
								"Cannot register resolved alias '" + resolvedAlias + "' (original: '" + alias +
								"') for name '" + resolvedName + "': It is already registered for name '" +
								registeredName + "'.");
					}
					checkForAliasCircle(resolvedName, resolvedAlias);
					this.aliasMap.remove(alias);
					this.aliasMap.put(resolvedAlias, resolvedName);
				}
				else if (!registeredName.equals(resolvedName)) {
					this.aliasMap.put(alias, resolvedName);
				}
			});
		}
	}
	
   /*解析別稱中是否有環*/
   protected void checkForAliasCircle(String name, String alias) {
		if (hasAlias(alias, name)) {
			throw new IllegalStateException("Cannot register alias '" + alias +
					"' for name '" + name + "': Circular reference - '" +
					name + "' is a direct or indirect alias for '" + alias + "' already");
		}
	}
	
	public String canonicalName(String name) {
		String canonicalName = name;
		// Handle aliasing...
		String resolvedName;
		do {
			resolvedName = this.aliasMap.get(canonicalName);
			if (resolvedName != null) {
				canonicalName = resolvedName;
			}
		}
		while (resolvedName != null);
		return canonicalName;
	}

}
SingletonBeanRegistry

單例bean的註冊介面定義如下:

public interface SingletonBeanRegistry {

	void registerSingleton(String beanName, Object singletonObject);
	
	@Nullable
	Object getSingleton(String beanName);

	boolean containsSingleton(String beanName);

	String[] getSingletonNames();

	int getSingletonCount();

	Object getSingletonMutex();

}

DefaultSingletonBeanRegistry

Spring單例類註冊的預設實現,這個類很重要。首先看下這個類的屬性定義如下:

    /** 單例物件快取*/
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

	/** 單例工程快取 */
	private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

	/** 提前暴露的物件快取*/
	private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);

	/** 已經註冊的單例物件集合,按照註冊順序排序 */
	private final Set<String> registeredSingletons = new LinkedHashSet<>(256);

	/** 併發下建立的單例物件 */
	private final Set<String> singletonsCurrentlyInCreation =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));

	/** 建立檢測中排除掉的bean集合 */
	private final Set<String> inCreationCheckExclusions =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));

	/** 被抑制異常的列表,可用於關聯相關原因 */
	@Nullable
	private Set<Exception> suppressedExceptions;

	/*是否併發銷燬bean的標誌*/
	private boolean singletonsCurrentlyInDestruction = false;

	/** 可廢棄的bean集合 */
	private final Map<String, Object> disposableBeans = new LinkedHashMap<>();

	/*名稱為name的bean持有的beans列表*/
	private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);

	/*名稱為name的bean與依賴的beans的對映關係*/
	private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);

	/*名稱為name的bean與被依賴的beans的對映關係*/
	private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);

單例類的獲取過程與迴圈依賴的實現原理

 獲取單例物件的執行流程如下:
 首先從單例物件快取中獲取物件,如果獲取不到或者單例物件正在被併發建立,那麼嘗試從提前暴露的單例物件快取中獲取物件,如果還是獲取不到,再從單例物件工廠中獲取物件,並放入提前暴露的物件快取中。原始碼如下:

@Nullable
	protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	//從單例物件快取中獲取物件
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
			synchronized (this.singletonObjects) {
		    	//從提前暴露的單例物件快取中獲取物件
				singletonObject = this.earlySingletonObjects.get(beanName);
				if (singletonObject == null && allowEarlyReference) {
					ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
					if (singletonFactory != null) {
					//從單例物件工廠中獲取物件,並放入提前暴露的物件快取中
						singletonObject = singletonFactory.getObject();
						this.earlySingletonObjects.put(beanName, singletonObject);
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		return singletonObject;
	}

 另外,還提供了從單例物件工廠ObjectFactory中獲取例項的方法如下:

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
		Assert.notNull(beanName, "Bean name must not be null");
		synchronized (this.singletonObjects) {
		// 首先重試直接從物件工廠中直接獲取例項,如果獲取不到,以同步的方式直接從singletonFactory獲取例項
			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 {
				  // 獲取例項
					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;
		}
	}
//建立物件前的快取判斷:物件是否在建立中和物件沒有被併發建立
protected void beforeSingletonCreation(String beanName) {
		if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
			throw new BeanCurrentlyInCreationException(beanName);
		}
	}
//物件建立結束後做快取清理
protected void afterSingletonCreation(String beanName) {
		if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
			throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
		}
	}
FactoryBeanRegistrySupport

 FactoryBeanRegistrySupport的主要作用是:對於實現了FactoryBean介面的單例類,提供了獲取單例類例項和獲取FactoryBean例項的方法。核心實現如下:

public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {

	/**  實現了FactoryBean的bean的快取 */
	private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);

    /**  從快取中獲取FactoryBean例項 */
	@Nullable
	protected Object getCachedObjectForFactoryBean(String beanName) {
		return this.factoryBeanObjectCache.get(beanName);
	}

   /*從FactoryBean例項中獲取物件例項*/
	protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
	  
	   /* FactoryBean是單例的 */
		if (factory.isSingleton() && containsSingleton(beanName)) {
			synchronized (getSingletonMutex()) {
			   /**  從快取中獲取FactoryBean例項 */
				Object object = this.factoryBeanObjectCache.get(beanName);
				if (object == null) {
				   /**  通過FactoryBean例項獲取單例物件 */
					object = doGetObjectFromFactoryBean(factory, beanName);
					Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
					if (alreadyThere != null) {
						object = alreadyThere;
					}
					else {
						if (shouldPostProcess) {
							if (isSingletonCurrentlyInCreation(beanName)) {
								return object;
							}
							beforeSingletonCreation(beanName);
							try {
								object = postProcessObjectFromFactoryBean(object, beanName);
							}
							catch (Throwable ex) {
								throw new BeanCreationException(beanName,
										"Post-processing of FactoryBean's singleton object failed", ex);
							}
							finally {
								afterSingletonCreation(beanName);
							}
						}
						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;
		}
	}

	private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
			throws BeanCreationException {
		Object object;
		try {
			if (System.getSecurityManager() != null) {
				AccessControlContext acc = getAccessControlContext();
				try {
					object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
				}
				catch (PrivilegedActionException pae) {
					throw pae.getException();
				}
			}
			else {
			//實現了FactoryBean介面,getObject()返回例項物件
				object = factory.getObject();
			}
		}
		catch (FactoryBeanNotInitializedException ex) {
			throw new BeanCurrentlyInCreationException(beanName, ex.toString());
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
		}
		if (object == null) {
			if (isSingletonCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(
						beanName, "FactoryBean which is currently in creation returned null from getObject");
			}
			object = new NullBean();
		}
		return object;
	}
}
ListableBeanFactory

 ListableBeanFactory提供根據各種條件獲取bean的配置清單:

public interface ListableBeanFactory extends BeanFactory {

    /*判斷是否有Bean的定義*/
	boolean containsBeanDefinition(String beanName);
   
   /*返回Bean的定義的計數*/
	int getBeanDefinitionCount();

   /*返回Bean的定義的名稱集合*/
	String[] getBeanDefinitionNames();
	
    /*返回可解析型別的Bean的定義的名稱集合*/
	String[] getBeanNamesForType(ResolvableType type);

	String[] getBeanNamesForType(@Nullable Class<?> type);

	String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);
	
   /*返回指定type的bean對映*/
	<T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException;

	<T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
			throws BeansException;
			
    /*返回指定註解型別annotationType的bean名稱*/
	String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType);

   /*返回指定註解型別annotationType的bean例項*/
	Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;

   /*返回指定bean名稱和註解型別annotationType的註解/
	@Nullable
	<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
			throws NoSuchBeanDefinitionException;

}

HierarchicalBeanFactory

 HierarchicalBeanFactory主要提供獲取父級BeanFactory:

public interface HierarchicalBeanFactory extends BeanFactory {

    /*返回BeanFactory的父級BeanFactory*/
	@Nullable
	BeanFactory getParentBeanFactory();

	boolean containsLocalBean(String name);

}

ConfigurableBeanFactory

 ConfigurableBeanFactory提供配置BeanFactory的各種方法:

public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {

   String SCOPE_SINGLETON = "singleton";

   String SCOPE_PROTOTYPE = "prototype";
   
   /*配置父級BeanFactory*/
   void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException;
   
   /*配置的類載入器,預設為執行緒上下文類載入*/
   void setBeanClassLoader(@Nullable ClassLoader beanClassLoader);
   
   /*獲取類載入器*/
   @Nullable
   ClassLoader getBeanClassLoader();
   
   /*型別匹配的時候設定臨時載入器,預設為空,簡單的使用標準類載入器*/
   void setTempClassLoader(@Nullable ClassLoader tempClassLoader);
   
   /*獲取臨時類載入器*/
   @Nullable
   ClassLoader getTempClassLoader();

   /*設定是否快取BeanMeta*/
   void setCacheBeanMetadata(boolean cacheBeanMetadata);

   boolean isCacheBeanMetadata();
   
   /*設定BeanExpressionResolver*/
   void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver);

   /*獲取BeanExpressionResolver*/
   @Nullable
   BeanExpressionResolver getBeanExpressionResolver();
   
   /*設定ConversionService,屬性轉換*/
   void setConversionService(@Nullable ConversionService conversionService);

   @Nullable
   ConversionService getConversionService();
   
   /*新增PropertyEditorRegistrar*/
   void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar);

   void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass);

   void copyRegisteredEditorsTo(PropertyEditorRegistry registry);

   void setTypeConverter(TypeConverter typeConverter);

   TypeConverter getTypeConverter();

   void addEmbeddedValueResolver(StringValueResolver valueResolver);

   boolean hasEmbeddedValueResolver();

   @Nullable
   String resolveEmbeddedValue(String value);
   
   /*新增BeanPostProcessor*/
   void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);

   int getBeanPostProcessorCount();

   void registerScope(String scopeName, Scope scope);

   String[] getRegisteredScopeNames();

   @Nullable
   Scope getRegisteredScope(String scopeName);

   AccessControlContext getAccessControlContext();

   void copyConfigurationFrom(ConfigurableBeanFactory otherFactory);

   void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException;

   void resolveAliases(StringValueResolver valueResolver);

   BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

   /*判斷是否是FactoryBean例項*/
   boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException;

   void setCurrentlyInCreation(String beanName, boolean inCreation);

   boolean isCurrentlyInCreation(String beanName);

   /*註冊依賴的Bean例項*/
   void registerDependentBean(String beanName, String dependentBeanName);

   String[] getDependentBeans(String beanName);

   String[] getDependenciesForBean(String beanName);

   void destroyBean(String beanName, Object beanInstance);
   
   void destroyScopedBean(String beanName);

   void destroySingletons();

}
AutowireCapableBeanFactory

 AutowireCapableBeanFactory提供建立bean,自動注入,初始化以及應用bean的後處理器。

public interface AutowireCapableBeanFactory extends BeanFactory {
	
	/*物件注入方式0,1,2,3,4*/
	int AUTOWIRE_NO = 0;

	int AUTOWIRE_BY_NAME = 1;
	
	int AUTOWIRE_BY_TYPE = 2;

	int AUTOWIRE_CONSTRUCTOR = 3;

	@Deprecated
	int AUTOWIRE_AUTODETECT = 4;
	
	/*建立例項*/
	<T> T createBean(Class<T> beanClass) throws BeansException;
	
	/*自動注入Bean*/
	void autowireBean(Object existingBean) throws BeansException;
	
	/*配置bean */
	Object configureBean(Object existingBean, String beanName) throws BeansException;

	Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;

	Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
	
	/*自動注入bean屬性*/
	void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
			throws BeansException;
	
	/*通過autowireBeanProperties方法應用PropertyValues*/
	void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException;

	Object initializeBean(Object existingBean, String beanName) throws BeansException;

	Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
			throws BeansException;
	
	/*初始化bean後應用BeanPostProcessors*/
	Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException;

	void destroyBean(Object existingBean);

	/*解析需要型別requiredType的bean*/
	<T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException;

	@Nullable
	Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException;

	/*解析依賴的bean*/
	@Nullable
	Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException;

}
ConfigurableListableBeanFactory

 BeanFactory配置清單,指定忽略型別和介面等。

public interface ConfigurableListableBeanFactory
		extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
	/*忽略依賴型別*/
	void ignoreDependencyType(Class<?> type);
	
	/*忽略依賴介面*/
	void ignoreDependencyInterface(Class<?> ifc);
	
	/*註冊可解析的依賴*/
	void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue);

	boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
			throws NoSuchBeanDefinitionException;

	/*獲取BeanDefinition根據beanName*/
	BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

	/*獲取beanName的迭代器*/
	Iterator<String> getBeanNamesIterator();

	/*清除Metadata快取*/
	void clearMetadataCache();
	
	/*冰凍不被修改bean definitions*/
	void freezeConfiguration();

	/*bean definitions是否被冰凍住*/
	boolean isConfigurationFrozen();

	/*初始化所有非懶載入的bean*/
	void preInstantiateSingletons() throws BeansException;
}

AbstractBeanFactory的核心實現

AbstractBeanFactory內部屬性定義
	/*父級BeanFactory*/
	@Nullable
	private BeanFactory parentBeanFactory;

	/*Bean的類載入器*/
	@Nullable
	private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

	/*Bean的臨時類載入器*/
	@Nullable
	private ClassLoader tempClassLoader;

	/*是否快取meta data資料標誌 */
	private boolean cacheBeanMetadata = true;

	/*bean definition中的表示式的解析策略*/
	@Nullable
	private BeanExpressionResolver beanExpressionResolver;

	/*屬性轉換,使用PropertyEditors替換*/
	@Nullable
	private ConversionService conversionService;

	/*應用到物件工廠中的屬性轉換器註冊*/
	private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<>(4);

	/*應用到物件工廠中的屬性轉換器*/
	private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>(4);

	/*型別轉換器,重寫預設PropertyEditor機制*/
	@Nullable
	private TypeConverter typeConverter;

	/*字串解析,應用於註解屬性值*/
	private final List<StringValueResolver> embeddedValueResolvers = new LinkedList<>();

	/*應用於建立bean的BeanPostProcessors*/
	private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

	/*標誌InstantiationAwareBeanPostProcessors是否已被註冊*/
	private boolean hasInstantiationAwareBeanPostProcessors;
	
	/*標誌DestructionAwareBeanPostProcessors是否已被註冊*/
	private boolean hasDestructionAwareBeanPostProcessors;

	/*Scope對映*/
	private final Map<String, Scope> scopes = new LinkedHashMap<>(8);

	@Nullable
	private SecurityContextProvider securityContextProvider;

	/*合併的RootBeanDefinition與名稱對映*/
	private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256);

	/*最後一次建立的bean集合*/
	private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));

	/*正在建立的bean的名稱*/
	private final ThreadLocal<Object> prototypesCurrentlyInCreation =
			new NamedThreadLocal<>("Prototype beans currently in creation");
AbstractBeanFactory的核心實現方法

 AbstractBeanFactory從BeanFactory獲取例項的核心實現如下:

doGetBean
public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args)
			throws BeansException {

		return doGetBean(name, requiredType, args, false);
	}

@SuppressWarnings("unchecked")
	protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
		
		/*獲取原始beanName,首先去除&符號開頭,然後從別稱快取map中get到原始beanName*/
		final String beanName = transformedBeanName(name);
		Object bean;
		
		/*首先嚐試從單例物件工廠中獲取例項*/
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			......
			/* 獲取例項*/
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			/*獲取父級BeanFactory*/ 
			BeanFactory parentBeanFactory = getParentBeanFactory();
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				String nameToLookup = originalBeanName(name);
				if (parentBeanFactory instanceof AbstractBeanFactory) {
					
					/*遞迴從父級BeanFactory獲取例項*/ 
					return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
							nameToLookup, requiredType, args, typeCheckOnly);
				}
				else if (args != null) {
					return (T) parentBeanFactory.getBean(nameToLookup, args);
				}
				else {
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
			}

			if (!typeCheckOnly) {
				markBeanAsCreated(beanName);
			}

			try {
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				/*檢測建立的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);
						}
					}
				}

				/*根據RootBeanDefinition建立Bean*/
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						try {
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							destroySingleton(beanName);
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				else if (mbd.isPrototype()) {
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						/*建立Prototype型別的Bean*/
						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);
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}

		/*檢測需要的型別是否與建立的例項型別匹配*/
		if (requiredType != null && !requiredType.isInstance(bean)) {
			try {
				T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
				if (convertedBean == null) {
					throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
				}
				return convertedBean;
			}
			catch (TypeMismatchException ex) {
		    ......
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
		}
		return (T) bean;
	}
	
/* 獲取例項*/
protected Object getObjectForBeanInstance(
			Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

		if (BeanFactoryUtils.isFactoryDereference(name)) {
			if (beanInstance instanceof NullBean) {
				return beanInstance;
			}
			if (!(beanInstance instanceof FactoryBean)) {
				throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
			}
		}

		if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
			return beanInstance;
		}
		/* 首先嚐試從FactoryBean快取中獲取例項,如果獲取不到,從FactoryBean獲取例項*/
		Object object = null;
		if (mbd == null) {
			object = getCachedObjectForFactoryBean(beanName);
		}
		if (object == null) {
			FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
			if (mbd == null && containsBeanDefinition(beanName)) {
				mbd = getMergedLocalBeanDefinition(beanName);
			}
			boolean synthetic = (mbd != null && mbd.isSynthetic());
			object = getObjectFromFactoryBean(factory, beanName, !synthetic);
		}
		return object;
	}

/*如果是子的BeanDefinition,需要合併父BeanDefinition的資訊*/
protected RootBeanDefinition getMergedBeanDefinition(
			String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
			throws BeanDefinitionStoreException {

		synchronized (this.mergedBeanDefinitions) {
			RootBeanDefinition mbd = null;

			if (containingBd == null) {
				mbd = this.mergedBeanDefinitions.get(beanName);
			}

			if (mbd == null) {
				if (bd.getParentName() == null) {
					if (bd instanceof RootBeanDefinition) {
						mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
					}
					else {
						mbd = new RootBeanDefinition(bd);
					}
				}
				else {
					BeanDefinition pbd;
					try {
						String parentBeanName = transformedBeanName(bd.getParentName());
						if (!beanName.equals(parentBeanName)) {
							pbd = getMergedBeanDefinition(parentBeanName);
						}
						else {
							BeanFactory parent = getParentBeanFactory();
							if (parent instanceof 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);
					}
					mbd = new RootBeanDefinition(pbd);
					mbd.overrideFrom(bd);
				}

				if (!StringUtils.hasLength(mbd.getScope())) {
					mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
				}

				if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
					mbd.setScope(containingBd.getScope());
				}

				if (containingBd == null && isCacheBeanMetadata()) {
					this.mergedBeanDefinitions.put(beanName, mbd);
				}
			}
			return mbd;
		}
	}

####### isTypeMatch
 最複雜方法原始碼分析isTypeMatch:

 /*判斷物件工廠中名稱name的例項是否型別匹配*/
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
		String beanName = transformedBeanName(name);

		/*檢測手動註冊的單例類*/
		Object beanInstance = getSingleton(beanName, false);
		if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
			if (beanInstance instanceof FactoryBean) {
				if (!BeanFactoryUtils.isFactoryDereference(name)) {
					
					/*返回建立FactoryBean建立的例項的型別*/
					Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);
					return (type != null && typeToMatch.isAssignableFrom(type));
				}
				else {
					return typeToMatch.isInstance(beanInstance);
				}
			}
			else if (!BeanFactoryUtils.isFactoryDereference(name)) {
				if (typeToMatch.isInstance(beanInstance)) {
					return true;
				}
				else if (typeToMatch.hasGenerics() && containsBeanDefinition(beanName)) {
					
					/*RootBeanDefinition獲取*/
					RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
					Class<?> targetType = mbd.getTargetType();
					if (targetType != null && targetType != ClassUtils.getUserClass(beanInstance) &&
							typeToMatch.isAssignableFrom(targetType)) {
						
						/*檢測原始類也匹配,確定暴露給代理*/
						Class<?> classToMatch = typeToMatch.resolve();
						return (classToMatch == null || classToMatch.isInstance(beanInstance));
					}
				}
			}
			return false;
		}
		else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
			/*沒有例項註冊*/
			return false;
		}

		
		/*沒有找到單例例項*/
		BeanFactory parentBeanFactory = getParentBeanFactory();
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			
			/*沒有找到單例例項,委託父類工程*/
			return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);
		}

		/*取出RootBeanDefinition*/
		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

		Class<?> classToMatch = typeToMatch.resolve();
		if (classToMatch == null) {
			classToMatch = FactoryBean.class;
		}
		Class<?>[] typesToMatch = (FactoryBean.class == classToMatch ?
				new Class<?>[] {classToMatch} : new Class<?>[] {FactoryBean.class, classToMatch});
		
		/*檢測bean definition的裝飾類*/
		BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
		if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
			RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
			Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
			if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
				return typeToMatch.isAssignableFrom(targetClass);
			}
		}

		Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch);
		if (beanType == null) {
			return false;
		}

		/*檢測bean是否在處理FactoryBean*/
		if (FactoryBean.class.isAssignableFrom(beanType)) {
			if (!BeanFactoryUtils.isFactoryDereference(name) && beanInstance == null) {
				beanType = getTypeForFactoryBean(beanName, mbd);
				if (beanType == null) {
					return false;
				}
			}
		}
		else if (BeanFactoryUtils.isFactoryDereference(name)) {
			beanType = predictBeanType(beanName, mbd, FactoryBean.class);
			if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) {
				return false;
			}
		}

		ResolvableType resolvableType = mbd.targetType;
		if (resolvableType == null) {
			resolvableType = mbd.factoryMethodReturnType;
		}
		if (resolvableType != null && resolvableType.resolve() == beanType) {
			return typeToMatch.isAssignableFrom(resolvableType);
		}
		return typeToMatch.isAssignableFrom(beanType);
	}

AbstractAutowireCapableBeanFactory核心實現

 AbstractAutowireCapableBeanFactory實現了預設的bean建立方法,擁有所有被RootBeanDefinition具體化的能力。屬性如下:

AbstractAutowireCapableBeanFactory內部屬性
	/*建立例項的初始化策略,預設使用CGLIB建立例項*/
	private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

	/*方法引數的解析策略*/
	@Nullable
	private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

	/*是否允許迴圈引用,預設 true*/
	private boolean allowCircularReferences = true;

	private boolean allowRawInjectionDespiteWrapping = false;

	 /*忽略的依賴檢測和注入的資料型別*/
	private final Set<Class<?>> ignoredDependencyTypes = new HashSet<>();

	 /*忽略的依賴檢測和注入的介面型別*/
	private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<>();

	 /*併發建立例項的名稱*/
	private final NamedThreadLocal<String> currentlyCreatedBean = new NamedThreadLocal<>("Currently created bean");

	/*FactoryBean的包裝類快取 */
	private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>(16);

	/*PropertyDescriptor快取*/
	private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache =
			new ConcurrentHashMap<>(256);

AbstractAutowireCapableBeanFactory核心方法

建立例項,廣播例項,呼叫post-processors核心方法如下:

createBean
	@Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
		
		/*獲取RootBeanDefinition*/
		RootBeanDefinition mbdToUse = mbd;

        /*解析bean的Class類*/
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}

		/*準備方法重寫*/
		try {
			mbdToUse.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
			
			/*初始化前對BeanPostProcessors進行處理,返回的是一個代理而不是目標物件*/
			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 {
		    /*建立例項*/
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			return beanInstance;
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
		}
	}

/*應用初始化前的post-processors,解析對於特殊的bean是否有 before-instantiation*/
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) {
					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
					if (bean != null) {
						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					}
				}
			}
			mbd.beforeInstantiationResolved = (bean != null);
		}
		return bean;
	}

/*對初始化前的bean進行InstantiationAwareBeanPostProcessor處理*/
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;
	}


 /*對初始化後的bean進行BeanPostProcessor處理*/
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {
			
		Object result = existingBean;
		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
			Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}

 具體建立bean的核心實現如下:

doCreateBean
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {

		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
		  
		   /*建立例項*/
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		
		/*獲取例項和Class型別*/
		final Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					
					/*使用post-processors修改合併的bean定義*/
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}

		/*檢測是否有提前暴露單例類*/
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isDebugEnabled()) {
				logger.debug("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		/*初始化類*/ 
		Object exposedObject = bean;
		try {
			
			/*廣播初始化的類*/ 
			populateBean(beanName, mbd, instanceWrapper);
			/*初始化類*/ 
			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) {
				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) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
						
						   /*將依賴的單例類加入到列表中*/
							actualDependentBeans.add(dependentBean);
						}
					}
					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.");
					}
				}
			}
		}

		try {
			
			/*如果有需要,註冊拋棄的bean*/ 
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}
populateBean

執行廣播bean的初始化實現如下:

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		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;
			}
		}

		/*給InstantiationAwareBeanPostProcessors介面修改bean的狀態*/
		/*在屬性被設定之前,在欄位注入的時候回被用到*/
		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() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			
			/*獲取屬性的注入型別*/
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			/*依據名稱注入屬性*/
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}

			/*依據型別注入屬性*/
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}

			pvs = newPvs;
		}

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

		if (hasInstAwareBpps || needsDepCheck) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			if (hasInstAwareBpps) {
				for (BeanPostProcessor bp : getBeanPostProcessors()) {
					if (bp instanceof InstantiationAwareBeanPostProcessor) {
						InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
						pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvs == null) {
							return;
						}
					}
				}
			}
			if (needsDepCheck) {
				checkDependencies(beanName, mbd, filteredPds, pvs);
			}
		}

		if (pvs != null) {
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

DefaultListableBeanFactory核心實現

DefaultListableBeanFactory內部屬性定義
	/* DefaultListableBeanFactory引用的快取 */
	private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories =
			new ConcurrentHashMap<>(8);

	/* DefaultListableBeanFactory的序列化id */
	@Nullable
	private String serializationId;

	/*標誌是否允許不同的定義有相同的名稱 */
	private boolean allowBeanDefinitionOverriding = true;

	/*是否允許懶載入beans*/
	private boolean allowEagerClassLoading = true;

	/*可選擇的依賴排序順序*/
	@Nullable
	private Comparator<Object> dependencyComparator;

	/*用來檢測bean definition 能否被自動注入的解析器*/
	private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver();

	/*依賴型別和對應的自動注入的值的對映*/
	private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);

	/*BeanDefinition快取*/
	private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);

	/*依賴型別和單例,非單例bean的對映*/
	private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);

	/*依賴型別和單例bean的對映*/
	private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);

	/*按照註冊順序的bean definition名稱集合*/
	private volatile List<String> beanDefinitionNames = new ArrayList<>(256);

	/*手動註冊的單例類名稱,按照註冊順序排序*/
	private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);

	/*固定配置了的bean definition名稱快取陣列*/
	@Nullable
	private volatile String[] frozenBeanDefinitionNames;

	/*標誌bean definition元資料能否快取為所有的bean*/
	private volatile boolean configurationFrozen = false;
DefaultListableBeanFactory核心實現方法
doGetBeanNamesForType

 根據給出的型別獲取已經註冊的bean名稱,判斷bean definition或者getObjectType方法返回的值是否是FactoryBean例項。

private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
		List<String> result = new ArrayList<>();

		/*檢測所有的beans*/
		for (String beanName : this.beanDefinitionNames) {
			
			/*判斷bean名稱是否是別稱*/
			if (!isAlias(beanName)) {
				try {
					RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
					
					/*判斷bean定義是否是完整*/
					if (!mbd.isAbstract() && (allowEagerInit ||
							(mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
									!requiresEagerInitForType(mbd.getFactoryBeanName()))) {
					
						boolean isFactoryBean = isFactoryBean(beanName, mbd);
						BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
						boolean matchFound =
								(allowEagerInit || !isFactoryBean ||
										(dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) &&
								(includeNonSingletons ||
										(dbd != null ? mbd.isSingleton() : isSingleton(beanName))) &&
								isTypeMatch(beanName, type);
						if (!matchFound && isFactoryBean) {
							
							beanName = FACTORY_BEAN_PREFIX + beanName;
							matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type);
						}
						if (matchFound) {
							result.add(beanName);
						}
					}
				}
				catch (CannotLoadBeanClassException ex) {
					if (allowEagerInit) {
						throw ex;
					}
					
					if (logger.isDebugEnabled()) {
						logger.debug("Ignoring bean class loading failure for bean '" + beanName + "'", ex);
					}
					onSuppressedException(ex);
				}
				catch (BeanDefinitionStoreException ex) {
					if (allowEagerInit) {
						throw ex;
					}
					
					if (logger.isDebugEnabled()) {
						logger.debug("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex);
					}
					onSuppressedException(ex);
				}
			}
		}

		for (String beanName : this.manualSingletonNames) {
			try {
				
				/*判斷是否是FactoryBean建立的例項*/
				if (isFactoryBean(beanName)) {
					if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
						result.add(beanName);
						continue;
					}
					
					beanName = FACTORY_BEAN_PREFIX + beanName;
				}
			
				/*匹配原始的bean型別*/
				if (isTypeMatch(beanName, type)) {
					result.add(beanName);
				}
			}
			catch (NoSuchBeanDefinitionException ex) {
				
				......
				
				if (logger.isDebugEnabled()) {
					logger.debug("Failed to check manually registered singleton with name '" + beanName + "'", ex);
				}
			}
		}
		return StringUtils.toStringArray(result);
	}
preInstantiateSingletons

 預初始化單例類

public void preInstantiateSingletons() throws BeansException {
		
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		/*觸發初始化所有非懶載入bean*/ 
		for (String beanName : beanNames) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				if (isFactoryBean(beanName)) {
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					if (bean instanceof FactoryBean) {
						final FactoryBean<?> factory = (FactoryBean<?>) bean;
						boolean isEagerInit;
						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
							isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
											((SmartFactoryBean<?>) factory)::isEagerInit,
									getAccessControlContext());
						}
						else {
							isEagerInit = (factory instanceof SmartFactoryBean &&
									((SmartFactoryBean<?>) factory).isEagerInit());
						}
						if (isEagerInit) {
							getBean(beanName);
						}
					}
				}
				else {
					getBean(beanName);
				}
			}
		}

		/*在回撥應用所有的beans的時候,觸發post-initialization*/
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}

相關推薦

SpringBean容器DefaultListableBeanFactory核心實現原始碼分析

文章目錄 DefaultListableBeanFactory的繼承結構 BeanFactory AliasRegistry BeanDefinitionRegistry

ScheduledThreadPoolExecutor定時週期任務的實現原始碼分析

ScheduledThreadPoolExecutor是一個定時任務執行緒池,相比於ThreadPoolExecutor最大的不同在於其阻塞佇列的實現 首先看一下其構造方法: 1 public ScheduledThreadPoolExecutor(int corePoolSize, 2

SpringIOC容器對數組,集合的相關bean的裝配

art prop emp pri val 對數 try ioc容器 blog <bean id="department" class="com.pojo.Department"> <property name="name" val

Spring bean 註冊的原始碼解析

前言 所謂 bean 的註冊,就是把在配置檔案中配置的 <bean> 節點載入配記憶體中,供後續使用。 bean的註冊主要分為兩個階段,一個是準備階段,就是對配置檔案進行解析,把配置檔案載入到記憶體中,以 Document 的形式存放;第二個階段是對 Document 進行操作,獲取其中的節

SpringBean多種實現切換方案

一個公共工程中的Spring配置檔案,可能會被多個工程引用。因為每個工程可能只需要公共工程中的一部分Bean,所以這些工程的Spring容器啟動時,需要區分開哪些Bean要創建出來。另一種場景是:想通過Properties檔案中的配置開關,就將Spring配置檔案中Bea

Springbean的例項化方式與IOC容器總結

提到spring,第一印象就是DI與IOC,雖然有概念上的解釋,但是要理解這些概念還是需要動手進行試驗。如果要深入瞭解spring的原來,那麼最先了解得就應該是spring容器。Spring提供了兩種型別的IOC容器實現:      1.beanFactory: IOC 容器

SpringBean的生命周期

spring bean生命周期 Spring 容器中的 Bean 是有生命周期的,Spring 允許在 Bean 在初始化完成後以及 Bean 銷毀前執行特定的操作,常用的設定方式有以下三種: (1)通過 <bean> 元素的 init-method/destroy-

SpringBean的配置方式之FactoryBean

alt mage -1 bsp image 技術分享 logs 指向 urn   Spring 中有兩種類型的 Bean, 一種是普通Bean, 另一種是工廠Bean, 即FactoryBean.   工廠 Bean 跟普通Bean不同, 其返回的對象不是指定類的一個實例,

半夜思考之查漏補缺 , Spring Bean 之間的依賴問題

為什麽 gte 每次 自己的 ont 打獵 不同 pro 自己 每次看書都會發現自己的不足 . 當一個 singten 的 Bean 依賴一個 prototype 的 Bean 時 , 如果不加註意 , 會發生一些奇怪的事情 , prototype 變為了 s

Springbean的作用範圍

pre 方法 context () 釋放資源 應用 生命 產生 ron singleton作用域:   Spring的scope的默認值是singleton   Spring 只會為每一個bean創建一個實例,並保持bean的引用. <bean id="bean的i

SpringBean的五個作用域

就會 clas web應用 import 銷毀 cstring tor 默認 global 當通過spring容器創建一個Bean實例時,不僅可以完成Bean實例的實例化,還可以為Bean指定特定的作用域。Spring支持如下5種作用域: singleton:單例模式,

spring bean生命周期

encoding 學習 tostring true ice ava initial oid pan 從頭開始學習spring(一) 傳統編程中,依賴關系比較多的情況下,導致維護成本直線上升,spring 采用Ioc對bean進行管理,減少了開發人員的工作量 正確理解spri

spring源碼--容器的基本實現

init turn try consumer ica not www ask queue 在工作中見得非常多的容器使用是:<beans xmlns="http://www.springframework.org/schema/beans" xml

springBean創建

AI nbsp ini csdn div 進行 BE 資源 href Spring中bean的加載過程:   1.獲取配置文件資源   2.對獲取的xml資源進行一定的處理檢驗   3.處理包裝資源   4.解析處理包裝過後的資源   5.加載提取bean並註冊(添加到be

SpringBean的生命周期討論

work cxf hello sys tex 操作 classpath system under 1、代碼和配置文件準備 1.1、測試類(user.java) 1 public class User { 2 private int id; 3 pri

SpringBean的理解以及@Bean的作用

是把 ring con 通過 自動配置 面向對象 ava 符號 反射 一、Bean是啥 1、Java面向對象,對象有方法和屬性,那麽就需要對象實例來調用方法和屬性(即實例化); 2、凡是有方法或屬性的類都需要實例化,這樣才能具象化去使用這些方法和屬性; 3、規律:凡是子類及

Springbean標簽的屬性和值:

lazy-init 獲取 bean 當前 宋體 指定 red pro style Spring中bean標簽的屬性和值: <bean name="user" class="com.pojo.User" init-method="intMethod" dest

知識儲備:SpringBean的生命週期(基於註解版)

一:前言 在Spring專案中,通常配置Spring都是使用XML的形式進行配置,配置bean是通過<bean></bean>標籤將bean加入IOC容器中,但在Spring註解版中,可以通過Java程式碼進行配置,即建立一個java類在其類頭上標註@Configurat

Springbean標籤的屬性和值:

Spring中bean標籤的屬性和值: <bean name="user" class="com.pojo.User" init-method="intMethod" destroy-method="destoryMethod" lazy-init="false" scope="sing

Spring筆記三】SpringBean(XML方式裝配)

       我們可以把 Spring 看作一個大型的工廠,而 Spring 容器中的 Bean 就是該工廠的產品。要想使用這個工廠生產和管理Bean,就需要在配置檔案中告訴它需要哪些 Be