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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值