spring源碼學習系列2.3-從beanDefinition到instance

本章探討beanDefinition到instance的過程-[color=red]註冊單例實例到容器singletonObjects中[/color]

從xml到document

從document到beanDefinition

[color=red]從beanDefiniton到instance[/color]


本文核心包括2部分:
4.1.實例化

4.2.初始化
這部分可以看到bean設置屬性值及執行方法的順序


[size=large]從beanDefinition到instance[/size]

從beanDefinition到instance的上下文入口,也是在
abstractApplicationContext.refresh:(abstractApplicationContext implements ConfigurableWebApplicationContext)
具體查看:
<spring源碼學習系列2.1-從xml到document>

abstractApplicationContext#refresh
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();

// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);

try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);

// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);

// Initialize message source for this context.
initMessageSource();

// Initialize event multicaster for this context.
initApplicationEventMulticaster();

// Initialize other special beans in specific context subclasses.
onRefresh();

// Check for listener beans and register them.
registerListeners();
//此處實例化bean
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);

// Last step: publish corresponding event.
finishRefresh();
}

catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}

// Destroy already created singletons to avoid dangling resources.
destroyBeans();

// Reset 'active' flag.
cancelRefresh(ex);

// Propagate exception to caller.
throw ex;
}
}
}

其中
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
實例化beanDefinition定義的bean

abstractApplicationContext#finishBeanFactoryInitialization
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}

// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}

// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);

// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();

// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}


[color=red][size=medium]這裏的CONVERSION_SERVICE_BEAN_NAME是何時定義的?[/size][/color]

// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();

[color=red][size=medium]此處實例化操作委託給beanFactory[/size][/color]-由此可見,applicationContext的核心還是beanFactory

[color=red][size=medium]applicationContext本身已經實現了ListableBeanFactory, HierarchicalBeanFactory等接口,爲什麼還要另在裏面定義一個AbstractRefreshableApplicationContext.beanFactory(DefaultListableBeanFactory)?[/size][/color]
其實跟蹤代碼可知,appContext實現了ListableBeanFactory, HierarchicalBeanFactory接口。最終也是調用getBeanFactory()來實現其功能。
這樣一來可以爲spring瘦身,不必把DefaultListableBeanFactory實現的功能在spring中,有寫一遍
二來讓spring看起來也像一個容器BeanFactory,只不過更高級點,實現了其他beanFactory沒有的功能


applicationContext
-------------------------------------------------------承上啓下的分割線----------------------------------------------
defaultListableBeanFactory
真正的實例化beanDefinition還是由beanFactory來實現


DefaultListableBeanFactory的源碼:
[url]http://grepcode.com/file/repo1.maven.org/maven2/org.springframework/spring-beans/3.2.7.RELEASE/org/springframework/beans/factory/support/DefaultListableBeanFactory.java/[/url]

[b][size=medium]創建RootBeanDefinition[/size][/b]
defaultListableBeanFactory#preInstantiateSingletons
public void preInstantiateSingletons() throws BeansException {
if (this.logger.isInfoEnabled()) {
this.logger.info("Pre-instantiating singletons in " + this);
}

List<String> beanNames;
synchronized (this.beanDefinitionMap) {
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
beanNames = new ArrayList<String>(this.beanDefinitionNames);
}

// Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
return ((SmartFactoryBean<?>) factory).isEagerInit();
}
}, getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
else {
getBean(beanName);
}
}
}
}

這裏開始循環實例化beanDefinition的bean,
首先判斷是否是factoryBean,這裏假設爲非factoryBean,現實情況也是非factoryBean居多


[color=red][size=medium]DefaultListableBeanFactory開始將創建bean的任務給父類AbstractBeanFactory-spring的單一職責原則[/size][/color]


defaultListableBeanFactory
創建rootBeanDefinition
-------------------------------------------------------父子類不同職責的分割線----------------------------------------------
abstractBeanFactory
getBean()


1.判斷instance是否已經存在,存在則返回
2.獲取RootBeanDefinition 委託AbstractAutowireCapableBeanFactory創建


abstractBeanFactory#getBean(String name):
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}


abstractBeanFactory#doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
該方法代碼量較大,讀者可直接查看源代碼,這裏對方法做的事做分段簡單描述:

1.判斷該類是否已實例化// Eagerly check singleton cache for manually registered singletons.
abstractBeanFactory#doGetBean
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}

這裏又兩部分操作:
一是判斷是否正在生成或已經生成
二是根據上一步得到的是真正的bean instance還是factoryBean,返回真正的bean instance

defaultSingletonBeanRegistry#getSingleton:(AbstractBeanFactory繼承了DefaultSingletonBeanRegistry)
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 != NULL_OBJECT ? singletonObject : null);
}


[b][color=green][size=medium]earlySingletonObjects添加數據[/size][/color][/b]

[b][size=medium][color=green]singletonFactories刪除數據[/color][/size][/b]


這裏有好幾個重要的屬性(數據結構):-[color=red][size=medium]注意觀察何時添加數據何時
刪除數據及存放什麼類型的數據[/size][/color]


[b][size=medium]doGetBean的過程就是相當於對這些數據結構就行操作,而向其添加刪除修改數據的過程就是算法[/size][/b]

[color=red][size=medium]this.singletonObjects換成普通的HashMap<String, Object>可以嗎?[/size][/color]

DefaultSingletonBeanRegistry
/** Cache of singleton objects: bean name --> bean instance */
[b][size=medium]Map<String, Object> singletonObjects[/size][/b]
單例列表-一級緩存

/** Cache of singleton factories: bean name --> ObjectFactory */
[b][size=medium]Map<String, ObjectFactory<?>> singletonFactories[/size][/b]
生成單例的工廠緩存-三級緩存

/** Cache of early singleton objects: bean name --> bean instance */
[b][size=medium]Map<String, Object> earlySingletonObjects[/size][/b]
早期單例列表-二級緩存

[color=red][size=medium]這裏的三級Cache是spring用來解決循環引用而設計的[/size][/color]
參考:http://www.jianshu.com/p/6c359768b1dc

最早是添加3級緩存數據
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}});
對於第一次生成實例而言,此處3個Cache都爲空

[color=red][size=medium]爲什麼需要3級Cache,將正在創建的bean直接放入二級緩存可以嗎,爲什麼要先放到singletonFactories()?[/size][/color]

/** Names of beans that are currently in creation (using a ConcurrentHashMap as a Set) */
[b][size=medium]Map<String, Boolean> singletonsCurrentlyInCreation[/size][/b]
正在創建bean列表

-------------------------------------------------------abstractBeanFactory#getObjectForBeanInstance:start----------------------------------------------
abstractBeanFactory#getObjectForBeanInstance:[color=red][size=medium]-此方法判斷bean是普通bean或者factoryBean[/size][/color]
/** Cache of singleton objects created by FactoryBeans: FactoryBean name --> object */
[b][size=medium]Map<String, Object> factoryBeanObjectCache[/size][/b]
該緩存可看着singletonObjects的子緩存,singletonObjects存的是factoryBean的實例,factoryBeanObjectCache存的是生成的對象getObject()的實例

[color=red][size=medium]singletonObjects是否存factory.getObject()產生的bean實例?[/size][/color]

如果是普通bean實例直接返回,否則從factoryBean.getObject()獲取,通過factoryBean.getOobject()的任務由abstractBeanFactory父類factoryBeanRegistrySupport來完成
[color=red][size=medium]factoryBeanRegistrySupport#getObjectFromFactoryBean
abstractoryBeanFactory每個父類都分工明確,這體現了java設計的單一職責原則。有時從類名稱就可以看出其作用[/size][/color]
-------------------------------------------------------abstractBeanFactory#getObjectForBeanInstance:end----------------------------------------------


2.緩存中沒有實例,則開始創建

2.1 判斷該bean是否正在創建
abstractBeanFactory
/** Names of beans that are currently in creation */
[b][size=medium]ThreadLocal<Object> prototypesCurrentlyInCreation[/size][/b]

2.2 判斷是否有父beanFactory並且在本次beanFactory中沒有該beanDefinition

[color=red][size=medium]是不是父beanFactory可以定義同一名稱的bean?[/size][/color]

2.3 標記該bean至少創建了一次
/** Names of beans that have already been created at least once */
[b][size=medium]Map<String, Boolean> alreadyCreated[/size][/b]

[b][color=green][size=medium]alreadyCreated添加數據[/size][/color][/b]

該語句作用不是很明確,以下爲其註釋
[quote]/**
* Mark the specified bean as already created (or about to be created).
* <p>This allows the bean factory to optimize its caching for repeated
* creation of the specified bean.
* @param beanName the name of the bean
*/[/quote]

2.4 獲取beanDefinition並創建
2.4.1 合成RootBeanDefinition
[b][size=medium]/** Map from bean name to merged RootBeanDefinition */[/size][/b]
Map<String, RootBeanDefinition> mergedBeanDefinitions

在document到beanDefinition的過程中,創建的是GenericBeanDefinition的對象

[b][color=green][size=medium]mergedBeanDefinitions添加數據[/size][/color][/b]

2.4.2 是否存在前置依賴,存在則先創建前置對象
[color=blue][size=medium]<bean ... depends-on="otherBeanName"/>[/size][/color]

DefaultSingletonBeanRegistry
/** Map between dependent bean names: bean name --> Set of dependent bean names */
[b][size=medium]Map<String, Set<String>> dependentBeanMap[/size][/b]
bean->前置bean

/** Map between depending bean names: bean name --> Set of bean names for the bean's dependencies */
[b][size=medium]Map<String, Set<String>> dependenciesForBeanMap[/size][/b]
前置bean->bean

[b][color=green][size=medium]dependentBeanMap添加數據[/size][/color][/b]

[b][color=green][size=medium]dependenciesForBeanMap添加數據[/size][/color][/b]

[color=red][size=medium]這2個緩存有什麼用?[/size][/color]

2.4.3 Create bean instance
這裏分三種情況(單例,原型,其他)
單例
abstractBeanFactory#doGetBean
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

這裏也分2步,先創建實例,再判斷是否是真實bean或者factoryBean返回

defaultSingletonBeanRegistry#getSingleton(模板方法)
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while the 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 recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
singletonObject = singletonFactory.getObject();
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
addSingleton(beanName, singletonObject);
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}

下面是每個語句作用的簡單描述:

/** List of suppressed Exceptions, available for associating related causes */
[b][size=medium]Set<Exception> suppressedExceptions[/size][/b]

[color=red][size=medium]suppressedExceptions的數據來源是什麼?[/size][/color]

/** Flag that indicates whether we're currently within destroySingletons */
[b][size=medium]boolean singletonsCurrentlyInDestruction[/size][/b]

/** Names of beans currently excluded from in creation checks (using a ConcurrentHashMap as a Set) */
[b][size=medium]Map<String, Boolean> inCreationCheckExclusions[/size][/b]

beforeSingletonCreation(beanName);
[b][color=green][size=medium]singletonsCurrentlyInCreation添加數據[/size][/color][/b]


singletonObject = singletonFactory.getObject(); [color=red][size=medium]-- 下面點分析[/size][/color]

afterSingletonCreation(beanName);
[b][color=green][size=medium]singletonsCurrentlyInCreation刪除數據[/size][/color][/b]

addSingleton(beanName, singletonObject);
/** Set of registered singletons, containing the bean names in registration order */
[b][size=medium]Set<String> registeredSingletons[/size][/b]

[b][color=green][size=medium]singletonObjects添加數據[/size][/color][/b]

[b][color=green][size=medium]singletonFactories刪除數據[/size][/color][/b]

[b][color=green][size=medium]earlySingletonObjects刪除數據[/size][/color][/b]

[b][color=green][size=medium]registeredSingletons添加數據[/size][/color][/b]


singletonFactory.getObject();
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}


[color=red][size=medium]此時,創建實例的任務轉移到了DefaultListableBeanFactory的父類AbstractAutowireCapableBeanFactory
[/size][/color]

DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory

AbstractAutowireCapableBeanFactory extends AbstractBeanFactory


abstractBeanFactory
getBean()
-------------------------------------------------------父子類不同職責的分割線----------------------------------------------
abstractAutowireCapableBeanFactory
createBean()


abstractAutowireCapableBeanFactory#createBean
/**
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.
* @see #doCreateBean
*/
@Override
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {

if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
// Make sure bean class is actually resolved at this point.
// 1.設置beanDefinition的beanClass屬性,如果沒處理的話
resolveBeanClass(mbd, beanName);

// Prepare method overrides.
try {
// 2.處理標籤<bean ... replace-method="" lookup-method="">
mbd.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}

try {
// 3.BeanPostProcessor擴展點 ,會回調InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation 和 InstantiationAwareBeanPostProcessor#postProcessAfterInitialization。如果返回bean不爲空,直接返回
//如:AbstractAutoProxyCreator#postProcessBeforeInstantiation 返回null,AbstractAutoProxyCreator#postProcessAfterInitialization並不會執行,而是初始化之後執行
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbd);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
// 4. 如果3過程沒有生成代理對象,則實例化bean
Object beanInstance = doCreateBean(beanName, mbd, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}

mbd.prepareMethodOverrides();
處理標籤[color=blue][size=medium]<bean ... replace-method="" lookup-method="">[/size][/color]


abstractAutowireCapableBeanFactory源碼:
[url]http://grepcode.com/file/repository.springsource.com/org.springframework/org.springframework.beans/3.2.2/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java/[/url]

abstractAutowireCapableBeanFactory#doCreateBean:
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
// 4.1 Instantiate the bean.-實例化
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {

instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 4.1.1 實例化beanClass,並創建BeanWrapImpl(beanInstance)
// BeanPostProcessor擴展點-回調SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
// 4.1.2 BeanPostProcessor擴展點-執行MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition,設置RootBeanDefinition的externallyManagedConfigMembers
// 何時處理這個屬性externallyManagedConfigMembers?
// 實現MergedBeanDefinitionPostProcessor的後置處理器有AutowiredAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
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.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 4.1.3 singletonFactories添加數據,earlySingletonObjects刪除數據,registeredSingletons添加數據
addSingletonFactory(beanName, new ObjectFactory<Object>() {
public Object getObject() throws BeansException {
// BeanPostProcessor擴展點 回調SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}

// 4.2 Initialize the bean instance.-初始化
Object exposedObject = bean;
try {
// 4.2.1 設置beanInstance屬性值
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
// 4.2.2 執行beanInstance的初始化方法,如init() afterPropertiesSet() aware的接口方法還有bean post processors
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);
}
}
// 4.3 優化
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<String>(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.");
}
}
}
}
// 4.4
// BeanPostProcessor擴展點-回調DestructionAwareBeanPostProcessor#postProcessBeforeDestruction
//如InitDestroyAnnotationBeanPostProcessor完成@PreDestroy註解的銷燬方法註冊和調用
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}

return exposedObject;
}

/** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */
[b][size=medium]Map<String, BeanWrapper> factoryBeanInstanceCache[/size][/b]

4.1.2
[color=red][size=medium]何時處理這個屬性externallyManagedConfigMembers?[/size][/color]

// 4.1.3
[b][size=medium]singletonFactories添加數據[/size][/b]

[b][size=medium]earlySingletonObjects刪除數據[/size][/b]

[b][size=medium]registeredSingletons添加數據[/size][/b]

// 4.3
根據dependentBeanMap優化實例化

4.2.1
AbstractAutowireCapableBeanFactory#populateBean
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
// 4.2.1.1獲取屬性值
PropertyValues pvs = mbd.getPropertyValues();

if (bw == null) {
if (!pvs.isEmpty()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}

// 4.2.1.1.1 BeanPostProcessor擴展點-改變特定實例的屬性值,而非beanDefinition中定義的。回調InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation方法
// 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.
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;
}

// 4.2.1.1.2 根據<beans default-autowire/> 自動添加符合添加的屬性值
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}

// Add property values based on autowire by type if applicable.
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) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
// 4.2.1.1.3 BeanPostProcessor擴展點-根據@Autowired @Resource @Required @ PersistenceContext等註解,回調InstantiationAwareBeanPostProcessor#postProcessPropertyValues添加屬性值。例如
// AutowiredAnnotationBeanPostProcessor#postProcessPropertyValues
// CommonAnnotationBeanPostProcessor#postProcessPropertyValues
// RequiredAnnotationBeanPostProcessor#postProcessPropertyValues
// PersistenceAnnotationBeanPostProcessor#postProcessPropertyValues
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;
}
}
}
}
// 4.2.1.1.4 執行依賴檢查
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
// 4.2.1.2 設置屬性值到beanInstance-應用明確的setter屬性注入
applyPropertyValues(beanName, mbd, bw, pvs);
}

[color=red][size=medium]4.2.1.1.2與4.2.1.1.3處理的屬性值會不會重複?
[/size][/color]


4.2.2
AbstractAutowireCapableBeanFactory#initializeBean
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
// 4.2.2.1 執行BeanNameAware#setBeanName,BeanClassLoaderAware#setBeanClassLoader,BeanFactoryAware#setBeanFactory等接口方法
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}

// 4.2.2.2 BeanPostProcessor擴展點 回調BeanPostProcessor#postProcessBeforeInitialization,執行spring自定義的beanPostProcessor,例如:
// ApplicationContextAwareProcessor 回調一些Aware接口,如EnvironmentAware,EmbeddedValueResolverAware, ResourceLoaderAware, ApplicationEventPublisherAware,MessageSourceAware,ApplicationContextAware
// InitDestroyAnnotationBeanPostProcessor 調用有@PostConstruct註解的初始化方法。
// BeanValidationPostProcessor 處理@Valid
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

// 4.2.2.3 執行InitializingBean#afterPropertiesSet() 自定義的init-method
try {
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}

// 4.2.2.4 BeanPostProcessor擴展點 回調BeanPostProcessor#postProcessAfterInitialization
// AspectJAwareAdvisorAutoProxyCreator(完成xml風格的AOP配置(<aop:config>)的目標對象包裝到AOP代理對象)

//AnnotationAwareAspectJAutoProxyCreator(完成@Aspectj註解風格(<aop:aspectj-autoproxy> @Aspect)的AOP配置的目標對象包裝到AOP代理對象),其返回值將替代原始的Bean對象;

//InfrastructureAdvisorAutoProxyCreator 處理<tx:transaction-annotation/>
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}

4.2.2.3
處理標籤[color=blue][size=medium]<bean ... init-method="">[/size][/color]


原型prototype


其它
request
session
global session


參考文章:
http://www.iteye.com/topic/1122859

http://yoyanda.blog.51cto.com/9675421/1721243

http://dba10g.blog.51cto.com/764602/1726519

http://m.blog.csdn.net/article/details?id=49283035

http://www.jianshu.com/p/6c359768b1dc

https://gavinzhang1.gitbooks.io/spring/content/zhun_bei_chuang_jian_bean.html

https://gavinzhang1.gitbooks.io/spring/content/chuang_jian_bean.html

BeanWrapper 設置和獲取屬性值
http://uule.iteye.com/blog/2105426

https://www.ibm.com/developerworks/cn/java/j-lo-beanannotation/

http://zhoujian1982318.iteye.com/blog/1696567

Spring中Autowired註解,Resource註解和xml default-autowire工作方式異同:
https://www.iflym.com/index.php/code/201211070001.html

bean的作用域 - Spring Framework reference 2.0.5 參考手冊中文版
http://doc.javanb.com/spring-framework-reference-zh-2-0-5/ch03s04.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章