好了,通过前面几章的讲解,我们才把BeanDefinition的定义给讲解完,下面接着讲解如何通过这些创建好的BeanDefinition来创建bean的实例(另外这章内容会比较多,看之前请做好心理准备@_@)
bean创建的大致流程:
1、调用BeanFactory的getBean(bean名称字符串)方法时,首先会从缓存中获取(就是一个CurrenthashMap对象)
2、如果从缓存中获取到了,则拿到这个bean对象,执行2_1。否则,执行3中的步骤
2_1、判断当前bean对象是否是一个FactoryBean,如果不是,执行2_1_1。如果是,则执行2_1_2
2_1_1、直接return这个bean,即已经获取到需要的bean了
2_1_2、从FactoryBean创建的bean的缓存中获取bean。如果获取到,则执行2_1_2_1。否则执行2_1_2_2
2_1_2_1、直接return这个bean,即已经获取到需要的bean了
2_1_2_2、调用这个FactoryBean的getObject()方法创建一个bean,然后把这个bean缓存到FactoryBean创建的bean的缓存中去,下次就能直接从缓存中获取到了(即,下次直接执行2_1_2_1)
3、准备创建这个bean对象(通过FactoryBean的getObject()方法创建的bean,和直接通过BeanFactory创建的bean的执行流程都大致相同)(通过bean的scope属性来确定是singleton还是prototype等范围,然后调用对应的方法来创建bean)
3_0、创建Bean之前,首先需要将该bean的创建标识设定好,表示该bean已经或即将被创建,以供其他地方使用这个状态
3_1、先在记录bean创建的缓存中缓存上当前bean(就是把当前要创建的bean的名称给缓存进去)
3_2、然后通过策略模式选择不同的策略对象来创建对象,比如:通过某个Factory()方法来初始化bean、通过执行bean的某个含参数的构造方法来创建对象、通过调用bean的无参构造函数来创建对象。
这几种策略最终都是通过反射的方式来执行方法(在创建之前首先检查访问修饰符,如果不是public修饰的,则调用setAccessible(true)来突破Java的语法限制,使得可以通过如私有的构造器来创建对象实例),创建对象的(这个时候还只是简单的创建了一个bean对象)
3_3、给bean的属性赋值(bean标签中不是会定义出一些属性和对应的属性值吗,那里面定义的东西就是在这一步得以实现的)
3_3、调用BeanPostProcessor的postProcessBeforeInitialization()方法(BeanPostProcessor对象可不止一个,而是一个集合。然后会有选择性的把集合中的其他BeanPostProcessor对象都执行一遍。如果有一个BeanPostProcessor执行后返回了null,则直接return null出去)
3_4、调用我们自定义的初始化方法(这里说的初始化方法不是说类的构造方法,而是通过初始化方法注解标识的那个方法)
3_5、调用BeanPostProcessor的postProcessAfterInitialization()方法,执行逻辑同3_3
4、将创建好的bean对象注册到缓存中去,方便下次直接获取
5、return bean
上面说的这些步骤其实并不准确和细节。就比如有可能还没执行步骤3,然后先执行了某个BeanPostProcessor的实现类,然后创建出一个代理对象,然后直接return 这个代理对象出去了。所以上面的步骤仅供参考。
另外bean如果实现了xxxAware类,那么Aware中的setxxx()方法也是在步骤3_3执行之后执行的。意思就是说,spring大致把bean的初始化分为了两个阶段:简单的创建了一个bean对象并且给简单给bean属性赋值 + bean的一些后置处理方法(自定义的初始化方法、BeanPostProcessor、xxxAware)
主代码块:下面的类是AbstractBeanFactory.java
/**
* Return an instance, which may be shared or independent, of the specified bean.
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @param typeCheckOnly whether the instance is obtained for a type check,
* not for actual use
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
@SuppressWarnings("unchecked")
//为什么我要从这个方法开始分析?因为我们通过IOC容器获取bean实例时,调用的就是这个方法
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//说先试着从单实例缓存中获取bean实例,因为如果要获取的bean是单实例的并且不是第一次获取这个bean(第一次获取就会创建改bean并且存放到缓存中去)
//单实例缓存:Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256) 其实就是一个concurrentHashMap而已
//见代码块1:
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实例对象(bean实例本身或它创建的对象(如FactoryBean)),就是说如果要获取的bean是一个FactoryBean对象(工厂bean))的话,就获取到该工厂创建的实例bean;否者就是获取该bean本身
//见代码块2:
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
//如果没有在单实例缓存中获取到这个bean,就走下面的逻辑
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
//如果创建这个bean存在循环引用的问题,则抛出异常
//见代码块3:
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
//获取父工厂
//见代码块4:
BeanFactory parentBeanFactory = getParentBeanFactory();
//如果当前工厂中没有指定的bean的定义信息,并且父工厂存在,则下面将从父工厂获取到bean实例
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
//将指定的bean标记为已经创建(或即将创建)
//见代码块5:
markBeanAsCreated(beanName);
}
try {
//将指定的BeanDefinition包装成RootBeanDefinition
//见代码块6:
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//实例化当前bean所依赖的其他bean(这里就是依赖注入(DI)的实现)
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 + "'");
}
registerDependentBean(dep, beanName);
getBean(dep);
}
}
//前面一系列准备工作都做完后,现在才开始创建当前bean的实例
// Create bean instance.
//判断指定bean是否是单实例bean
//见代码块7:
if (mbd.isSingleton()) {
//创建bean实例,ObjectFactory对象就是到时候创建bean实例的时候使用到的工厂bean,ObjectFactory和BeanFactory类似,都是用于创建bean实例的,详解见:内部代码块1:
//见代码块8:
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
//ObjectFactory工厂创建Bean实例需要调用的方法
//见代码块9:
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实例的对象,可以是bean实例本身或它创建的对象(如FactoryBean),应该和上面出现的代码块2的方法类似
//见代码块10:
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
//判断当前bean是否是原型bean
//见代码块11:
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
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;
}
}
// Check if required type matches the type of the actual bean instance.
//检查所需的类型(Class类型)与实际bean实例的类型是否匹配,不匹配则进行转换
if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
//返回bean实例
return (T) bean;
}
代码块1:getSingleton(beanName)
DefaultSingletonBeanRegistry.class
@Override
public Object getSingleton(String beanName) {
//见内部代码块1:
return getSingleton(beanName, true);
}
DefaultSingletonBeanRegistry.class
内部代码块1:
/**
* Return the (raw) singleton object registered under the given name.
* <p>Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
//返回在给定名称下注册的(原始)单例对象。检查已经实例化的单例,并允许对当前创建的单例对象的早期引用(解析循环引用)
//我感觉这个方法里面通过earlySingletonObjects就能够解决循环引用的问题
//试想一下循环引用的根本原因是两个对象因为相互引用对方成为自己的一个属性,结果两个对象到头来都没引用到对方,就导致最后两个对象都没创建完成。
//如果我让一个对象能够提前被另一个对象引用,是不是就解决了循环引用的问题?对吧!
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);
}
代码块2:getObjectForBeanInstance(sharedInstance, name, beanName, null)
AbstractBeanFactory.class
/**
* Get the object for the given bean instance, either the bean
* instance itself or its created object in case of a FactoryBean.
* @param beanInstance the shared bean instance
* @param name name that may include factory dereference prefix
* @param beanName the canonical bean name
* @param mbd the merged bean definition
* @return the object to expose for the bean
*/
//获取bean实例本身或则该bean实例创建的实例(因为这个bean实例是一个工厂bean)
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
//直接返回bean实例本身
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
Object object = null;
if (mbd == null) {
//尝试从缓存中获取,FactoryBean创建的Bean实例
//见:内部代码块1
object = getCachedObjectForFactoryBean(beanName);
}
//缓存中没有找到,所以由FactoryBean创建出实例化对象
if (object == null) {
// Return bean instance from factory.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
//FactoryBean创建出Bean实例对象
//见,内部代码块2
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
内部代码块1:
/**
* Obtain an object to expose from the given FactoryBean, if available
* in cached form. Quick check for minimal synchronization.
* @param beanName the name of the bean
* @return the object obtained from the FactoryBean,
* or {@code null} if not available
*/
protected Object getCachedObjectForFactoryBean(String beanName) {
//由FactoryBean创建的单例对象的缓存:FactoryBean名称——>对象
Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<String, Object>(16);
Object object = this.factoryBeanObjectCache.get(beanName);
return (object != NULL_OBJECT ? object : null);
}
内部代码块2:
/**
* Obtain an object to expose from the given FactoryBean.
* @param factory the FactoryBean instance
* @param beanName the name of the bean
* @param shouldPostProcess whether the bean is subject to post-processing
* @return the object obtained from the FactoryBean
* @throws BeanCreationException if FactoryBean object creation failed
* @see org.springframework.beans.factory.FactoryBean#getObject()
*/
//获取要从给定的FactoryBean公开的对象。
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
//如果FactoryBean是单例的,并且FactoryBean存在单例缓存中
if (factory.isSingleton() && containsSingleton(beanName)) {
synchronized (getSingletonMutex()) {
//先尝试从,由FactoryBean创建的单例对象的缓存:FactoryBean名称——>对象,中获取Bean实例
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
//缓存中没有获取到时,真正通过FactoryBean创建Bean实例
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (e.g. because of circular reference processing triggered by custom getBean calls)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
if (object != null && shouldPostProcess) {
try {
//调用Bean实例的后置处理器,处理bean实例
//见,内部代码块3
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
}
//把FactoryBean创建的Bean实例,缓存进FactoryBean创建的单例对象的缓存中:FactoryBean名称——>对象
this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT));
}
}
return (object != NULL_OBJECT ? object : null);
}
}
else {
//真正通过BeanFactory创建Bean实例
Object object = doGetObjectFromFactoryBean(factory, beanName);
//如果实例化出的Bean能够执行后置处理器方法,则执行Bean的后置处理器方法
if (object != null && shouldPostProcess) {
try {
//调用Bean实例的后置处理器,处理bean实例
//见,内部代码块3
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
内部代码块3:
/**
* Post-process the given object that has been obtained from the FactoryBean.
* The resulting object will get exposed for bean references.
* <p>The default implementation simply returns the given object as-is.
* Subclasses may override this, for example, to apply post-processors.
* @param object the object obtained from the FactoryBean.
* @param beanName the name of the bean
* @return the object to expose
* @throws org.springframework.beans.BeansException if any post-processing failed
*/
//对从FactoryBean获得的给定对象进行后处理。*结果对象将公开为bean引用。*
//默认实现简单地返回给定的对象。子类可以覆盖这个,例如,应用后置处理器。
//具体的实现类,见,内部代码块4
protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException {
return object;
}
内部代码块4:
AbstractAutowireCapableBeanFactory.class
/**
* Applies the {@code postProcessAfterInitialization} callback of all
* registered BeanPostProcessors, giving them a chance to post-process the
* object obtained from FactoryBeans (for example, to auto-proxy them).
* @see #applyBeanPostProcessorsAfterInitialization
*/
//调用BeanPostProcessors的AfterInitialization()方法,如对Bean实例进行自动代理
@Override
protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
//见,内部代码块5
return applyBeanPostProcessorsAfterInitialization(object, beanName);
}
内部代码块5:
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
//getBeanPostProcessors()返回注册到工厂中的所有beanpostprocessor集合
//就是返回这个属性:List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();
//如果某个beanPostProcessors处理后的Bean实例等于空,则直接返回。否则,返回所有的beanPostProcessors 处理后的对象
//注意:BeanPostProcessor是一个通用的类,它不需要某个bean来单独实现(继承)它,它只是一个普通的bean而已
//我们只需要把实现了BeanPostProcessor的实现类向普通bean一样,写入到配置文件中,IOC容器就会通过ConfigurableBeanFactory.addBeanPostProcessor()方法,
//将BeanPostProcessor的那个实现类注册到IOC容器中(可以注册多个BeanPostProcessor)。然后就能够通过下面的方法getBeanPostProcessors()) 得到了。
//然后IOC创建每个bean实例时,都会调用所有的BeanPostProcessor中的方法,当然我们可以根据BeanPostProcessor的方法中的第二个入参来编写针对某个bean
//的特别的处理逻辑
//BeanPostProcessor的执行时机:在bean正常实例化后(执行了bean的构造方法,属性已经正常赋值),在自定义的初始化方法的前后执行
//BeanPostProcessor的介绍链接:https://blog.csdn.net/qq_38526573/article/details/88086752
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
代码块3:isPrototypeCurrentlyInCreation(beanName)
AbstractBeanFactory.class
/**
* Return whether the specified prototype bean is currently in creation
* (within the current thread).
* @param beanName the name of the bean
*/
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
//ThreadLocal<Object> prototypesCurrentlyInCreation
//获取当前正在创建的bean的名称
Object curVal = this.prototypesCurrentlyInCreation.get();
//判断当前正在创建的bean的名称是否等于当前指定的bean的名称或者包含了当前指定的bean的名称
return (curVal != null &&
(curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
}
代码块4:getParentBeanFactory()
AbstractBeanFactory.class
@Override
//直接从当前BeanFactory中获取到父工厂
public BeanFactory getParentBeanFactory() {
return this.parentBeanFactory;
}
代码块5:markBeanAsCreated(beanName)
AbstractBeanFactory.class
/**
* 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
*/
//将指定的bean标记为已经创建(或即将创建)
protected void markBeanAsCreated(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
synchronized (this.mergedBeanDefinitions) {
if (!this.alreadyCreated.contains(beanName)) {
// Let the bean definition get re-merged now that we're actually creating
// the bean... just in case some of its metadata changed in the meantime.
clearMergedBeanDefinition(beanName);
this.alreadyCreated.add(beanName);
}
}
}
}
代码块6:getMergedLocalBeanDefinition(beanName)
属于类:AbstractBeanFactory.class
/**
* Return a merged RootBeanDefinition, traversing the parent bean definition
* if the specified bean corresponds to a child bean definition.
* @param beanName the name of the bean to retrieve the merged definition for
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
//返回一个合并的RootBeanDefinition,遍历父bean定义如果指定的bean对应于子bean定义。
//遍历当前bean定义的父bean定义,然后合并父bean定义和当前bean定义成RootBeanDefinition
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
//首先快速检查并发映射,并使用最少的锁。
//尝试从合并BeanDefinition缓存中获取(RootBeanDefinition缓存)
//见,内部代码块1
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null) {
return mbd;
}
//合并BeanDefinitin(创建RootBeanDefinition)
//见,内部代码块2
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
内部代码块1:
/** Map from bean name to merged RootBeanDefinition */
//从bean名称映射到合并的RootBeanDefinition
//这个Map,就是Bean实例名称对应的RootBeanDefinition的缓存
private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<String, RootBeanDefinition>(256);
内部代码块2:
/**
* Return a RootBeanDefinition for the given top-level bean, by merging with
* the parent if the given bean's definition is a child bean definition.
* @param beanName the name of the bean definition
* @param bd the original bean definition (Root/ChildBeanDefinition)
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
//通过合并,返回给定顶级bean的RootBeanDefinition如果给定bean的定义是子bean定义,则为父bean。
//就是将当前BeanDefinition和当前BeanDefinition的父BeanDefinition进行合并
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
throws BeanDefinitionStoreException {
//合并BeanDefinitin(创建RootBeanDefinition)
//见,内部代码块3
return getMergedBeanDefinition(beanName, bd, null);
}
内部代码块3:
/**
* Return a RootBeanDefinition for the given bean, by merging with the
* parent if the given bean's definition is a child bean definition.
* @param beanName the name of the bean definition
* @param bd the original bean definition (Root/ChildBeanDefinition)
* @param containingBd the containing bean definition in case of inner bean,
* or {@code null} in case of a top-level bean
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
//合并BeanDefinitin
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, BeanDefinition containingBd)
throws BeanDefinitionStoreException {
synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
mbd = this.mergedBeanDefinitions.get(beanName);
}
if (mbd == null) {
if (bd.getParentName() == null) {
// Use copy of given root bean definition.
if (bd instanceof RootBeanDefinition) {
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
}
else {
mbd = new RootBeanDefinition(bd);
}
}
else {
// Child bean definition: needs to be merged with parent.
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);
}
// Deep copy with overridden values.
mbd = new RootBeanDefinition(pbd);
mbd.overrideFrom(bd);
}
// Set default singleton scope, if not configured before.
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
}
// A bean contained in a non-singleton bean cannot be a singleton itself.
// Let's correct this on the fly here, since this might be the result of
// parent-child merging for the outer bean, in which case the original inner bean
// definition will not have inherited the merged outer bean's singleton status.
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}
// Cache the merged bean definition for the time being
// (it might still get re-merged later on in order to pick up metadata changes)
if (containingBd == null && isCacheBeanMetadata()) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
return mbd;
}
}
代码块7:isSingleton()
AbstractBeanFactory.class
/**
* Return whether this a <b>Singleton</b>, with a single shared instance
* returned from all calls.
* @see #SCOPE_SINGLETON
*/
@Override
//判断指定bean是否是单实例bean
public boolean isSingleton() {
return SCOPE_SINGLETON.equals(scope) || SCOPE_DEFAULT.equals(scope);
}
代码块8:getSingleton(beanName, new ObjectFactory<Object>(){})
AbstractBeanFactory.class
/**
* Return the (raw) singleton object registered under the given name,
* creating and registering a new one if none registered yet.
* @param beanName the name of the bean
* @param singletonFactory the ObjectFactory to lazily create the singleton
* with, if necessary
* @return the registered singleton object
*/
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
//尝试从单例对象的缓存中获取bean实例(单实例对象缓存:Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256))
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
//当这个工厂的单例对象被销毁时,不允许创建单例bean(不要在销毁方法实现中向BeanFactory请求bean)
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 + "'");
}
//单例对象创建前执行的回调方法,见:内部代码块1
beforeSingletonCreation(beanName);
//感觉没必要深究的一些列操作
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
//调用singletonFactory的getObject()方法创建Bean实例,该方法的具体实现在 "主代码块"的“见代码块8:”中有写,
//在"主代码块"的“见代码块8:”我们可以看到getObject()方法里面是通过调用createBean(beanName, mbd, args)方法
//来创建bean实例的,该方法的具体详解见:代码块9:
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 != NULL_OBJECT ? singletonObject : null);
}
}
内部代码块1:
/**
* Callback before singleton creation.
* <p>The default implementation register the singleton as currently in creation.
* @param beanName the name of the singleton about to be created
* @see #isSingletonCurrentlyInCreation
*/
//在单例创建之前回调。默认的实现会执行的操作:注册单例为当前正在创建。
protected void beforeSingletonCreation(String beanName) {
//当前在创建检查中被排除的bean的名称
//inCreationCheckExclusions = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));
//当前正在创建的bean的名称
//singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
代码块9:createBean(beanName, mbd, args)
AbstractAutowireCapableBeanFactory.class
/**
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.
* @see #doCreateBean
*/
//真正创建bean实例的方法,也就是说执行到这里才开始真正创建bean实例
//这个类的中心方法:创建一个bean实例,*填充bean实例,应用后处理程序,等等。
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
// 解析出当前bean的Class对象
//为指定的bean定义解析bean类,将bean类名解析为类引用(如有必要),并将解析后的类存储在bean定义中以供以后使用。具体实现自行深究
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
//准备方法覆盖,不知道这里是什么意思
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
//给beanpostprocessor一个机会,来返回代理后的bean,而不是目bean实例,见:内部代码块1
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);
}
//真正创建指定bean实例的方法,见:内部代码块2
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
//返回Bean实例
return beanInstance;
}
内部代码块1:创建bean的代理对象
/**
* Apply before-instantiation post-processors, resolving whether there is a
* before-instantiation shortcut for the specified bean.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @return the shortcut-determined bean instance, or {@code null} if none
*/
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) {
//执行InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation()方法
//InstantiationAwareBeanPostProcessor是BeanPostProcessor的一个实现类
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
//执行BeanPostProcessor的postProcessAfterInitialization()方法
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
内部代码块2:
/**
* Actually create the specified bean. Pre-creation processing has already happened
* at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
* <p>Differentiates between default bean instantiation, use of a
* factory method, and autowiring a constructor.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a new instance of the bean
* @throws BeanCreationException if the bean could not be created
* @see #instantiateBean
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
*/
//创建指定的bean实例
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
// Instantiate the bean.
//创建Bean的包装对象BeanWrapper
//BeanWrapper是javaBean的一个基础结构的中心接口,提供了分析和操作标准javabean的操作:获取和设置属性值的能力(单独或批量),获取属性描述符,查询属性的可读性/可写性
//BeanWrapper扮演的其实就是Bean实例的一个访问器角色,使能够更方便的访问bean实例的属性等
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//创建bean实例,见:内部代码块3
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//获取bean实例对象(因为被包装在了BeanWrapper中了)
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
//获取bean实例的类型(Class对象)
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
//将bean实例类型赋值给BeanDefinition
mbd.resolvedTargetType = beanType;
// Allow post-processors to modify the merged bean definition.
//允许后处理程序修改合并的bean定义
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//获取到BeanPostProcessor的集合,然后遍历,取出所有的MergedBeanDefinitionPostProcessor,
//然后调用它的postProcessMergedBeanDefinition方法
//具体作用不清楚,应该有合并的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;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
//急切地缓存单例以便能够解析循环引用
//甚至当由生命周期接口(如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");
}
//添加指定的单例工厂来构建指定的单例如果有必要。
//见:内部代码块9
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//给Bean实例填充属性值,见:内部代码块10
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
//初始化给定的bean实例,应用工厂回调init方法和bean后处理器(这里面有一些列回调方法的执行))。
//见:内部代码块12
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) {
//返回在给定名称下注册的(原始)单例对象
//见:内部代码块17
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.");
}
}
}
}
// Register bean as disposable.
try {
//将给定的bean添加到工厂的一次性bean列表中
//见:内部代码块18
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
内部代码块3:创建bean实例
/**
* Create a new instance for the specified bean, using an appropriate instantiation strategy:
* factory method, constructor autowiring, or simple instantiation.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return BeanWrapper for the new instance
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
* @see #instantiateBean
*/
//为指定的bean创建一个新实例,使用适当的实例化策略:factory方法、构造函数自动装配或简单实例化。
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
if (mbd.getFactoryMethodName() != null) {
//通过factory方法创建bean实例,暂时不深究,自行百度
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
//构造函数自动装配?????
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
// Need to determine the constructor...
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// No special handling: simply use no-arg constructor.
//不需要特殊处理:只需使用无参数构造函数。 //见:内部代码块4
return instantiateBean(beanName, mbd);
}
内部代码块4:无参数构造函数创建bean实例
/**
* Instantiate the given bean using its default constructor.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @return BeanWrapper for the new instance
*/
//使用给定bean的默认构造函数实例化它。
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
return getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
}, getAccessControlContext());
}
else {
//创建bean实例
//getInstantiationStrategy() 见:内部代码块5
//instantiate(mbd, beanName, parent) 见:内部代码块6
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
//把bean实例包装为BeanWrapper
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
内部代码块5:
/**
* Return the instantiation strategy to use for creating bean instances.
*/
//InstantiationStrategy 接口:
//接口,负责创建与根bean定义对应的实例。这是拉出一个战略,因为各种方法是可能的,包括使用CGLIB动态创建子类来支持方法注入。
protected InstantiationStrategy getInstantiationStrategy() {
return this.instantiationStrategy;
}
内部代码块6:instantiate(mbd, beanName, parent)
@Override
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
if (bd.getMethodOverrides().isEmpty()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
@Override
public Constructor<?> run() throws Exception {
return clazz.getDeclaredConstructor((Class[]) null);
}
});
}
else {
//得到bean定义类对象的构造方法对象
constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
//通过构造方法对象,创建出bean实例,并返回
//见:内部代码块7
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
内部代码块7:
/**
* Convenience method to instantiate a class using the given constructor.
* <p>Note that this method tries to set the constructor accessible if given a
* non-accessible (that is, non-public) constructor.
* @param ctor the constructor to instantiate
* @param args the constructor arguments to apply
* @return the new instance
* @throws BeanInstantiationException if the bean cannot be instantiated
* @see Constructor#newInstance
*/
//使用给定构造函数实例化类的便利方法。注意,如果给定一个不可访问(即非公共)的构造函数,此方法将尝试设置可访问的构造函数
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
Assert.notNull(ctor, "Constructor must not be null");
try {
//设置构造方法的访问修饰符(如果是私有构造方法,会将构造方法设置为可以访问)
//见:内部代码块8
ReflectionUtils.makeAccessible(ctor);
//调用构造方法实例化bean对象
return ctor.newInstance(args);
}
catch (InstantiationException ex) {
throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
}
catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
}
catch (InvocationTargetException ex) {
throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
}
}
内部代码块8:
/**
* Make the given constructor accessible, explicitly setting it accessible
* if necessary. The {@code setAccessible(true)} method is only called
* when actually necessary, to avoid unnecessary conflicts with a JVM
* SecurityManager (if active).
* @param ctor the constructor to make accessible
* @see java.lang.reflect.Constructor#setAccessible
*/
//使给定的构造函数可访问(必要时显式地将其设置为accessible,即调用setAccessible(true)方)
public static void makeAccessible(Constructor<?> ctor) {
if ((!Modifier.isPublic(ctor.getModifiers()) ||
!Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
ctor.setAccessible(true);
}
}
内部代码块9:
/**
* Add the given singleton factory for building the specified singleton
* if necessary.
* <p>To be called for eager registration of singletons, e.g. to be able to
* resolve circular references.
* @param beanName the name of the bean
* @param singletonFactory the factory for the singleton object
*/
//如果需要,添加指定的单例工厂来构建指定的单例。被要求立即注册单例,例如能够解析循环引用。
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
//单例对象的缓存:bean名称——> bean实例
//Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
if (!this.singletonObjects.containsKey(beanName)) {
//单例工厂的缓存:bean名——> ObjectFactory
//Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);
this.singletonFactories.put(beanName, singletonFactory);
//早期单例对象的缓存:bean名称——> bean实例
//Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);
this.earlySingletonObjects.remove(beanName);
//一组已注册的单例,包含按注册顺序排列的bean名称
//Set<String> registeredSingletons = new LinkedHashSet<String>(256);
this.registeredSingletons.add(beanName);
}
}
}
内部代码块10:populateBean(beanName, mbd, instanceWrapper)
/**
* Populate the bean instance in the given BeanWrapper with the property values
* from the bean definition.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param bw BeanWrapper with bean instance
*/
//用属性值填充给定BeanWrapper中的bean实例,来自bean定义
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
//获取bean的所有属性名
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;
}
}
// 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.
//给任何实例化awarebeanpostprocessor修改的机会
//在属性设置之前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;
}
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);
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);
}
}
//给属性赋值 见,内部代码块11
applyPropertyValues(beanName, mbd, bw, pvs);
}
内部代码块11:applyPropertyValues(beanName, mbd, bw, pvs) 给属性赋值
/**
* Apply the given property values, resolving any runtime references
* to other beans in this bean factory. Must use deep copy, so we
* don't permanently modify this property.
* @param beanName the bean name passed for better exception information
* @param mbd the merged bean definition
* @param bw the BeanWrapper wrapping the target object
* @param pvs the new property values
*/
//应用给定的属性值
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs == null || pvs.isEmpty()) {
return;
}
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
if (System.getSecurityManager() != null) {
if (bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
}
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
original = mpvs.getPropertyValueList();
}
else {
original = Arrays.asList(pvs.getPropertyValues());
}
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// Create a deep copy, resolving any references for values.
List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
boolean resolveNecessary = false;
for (PropertyValue pv : original) {
if (pv.isConverted()) {
deepCopy.add(pv);
}
else {
//属性名称 如:bean的name属性的名称是:name
String propertyName = pv.getName();
//属性的值对象 如:bean的name属性的值的对象:TypedStringValue: value [张三], target type [null]
Object originalValue = pv.getValue();
//值对象解析后的值 如:张三
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
//判断对应的属性值是否可写
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
//给bean实例的属性赋值
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// Possibly store converted value in merged bean definition,
// in order to avoid re-conversion for every created bean instance.
if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
}
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
}
else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) {
mpvs.setConverted();
}
// Set our (possibly massaged) deep copy.
try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
内部代码块12:initializeBean(beanName, exposedObject, mbd)
/**
* Initialize the given bean instance, applying factory callbacks
* as well as init methods and bean post processors.
* <p>Called from {@link #createBean} for traditionally defined beans,
* and from {@link #initializeBean} for existing bean instances.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @return the initialized bean instance (potentially wrapped)
* @see BeanNameAware
* @see BeanClassLoaderAware
* @see BeanFactoryAware
* @see #applyBeanPostProcessorsBeforeInitialization
* @see #invokeInitMethods
* @see #applyBeanPostProcessorsAfterInitialization
*/
//初始化给定的bean实例,应用工厂回调*以及init方法和bean后处理器。*
//调用从{@link #createBean}为传统定义的bean, *和从{@link #initializeBean}为现有的bean实例。
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
//判断当前Bean实例是否实现了Aware接口,如果是,则执行Aware对应的方法
//见:内部代码块13
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
//返回这个bean定义是否是“合成的”,也就是说,不是由应用程序本身定义的
if (mbd == null || !mbd.isSynthetic()) {
//执行所有BeanPostProcessors中的postProcessBeforeInitialization()方法
//返回被所有BeanPostProcessors修饰的最后一个最新的对象
//见:内部代码块14
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//检查bean是实现了InitializingBean还是定义了它一个自定义的init方法,并调用必要的回调
//见:内部代码块15
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
//执行所有BeanPostProcessors中的postProcessAfterInitialization()方法
//返回被所有BeanPostProcessors修饰的最后一个最新的对象
//见:内部代码块16
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
内部代码块13:
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
内部代码块14:
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
内部代码块15:invokeInitMethods(beanName, wrappedBean, mbd);
/**
* Give a bean a chance to react now all its properties are set,
* and a chance to know about its owning bean factory (this object).
* This means checking whether the bean implements InitializingBean or defines
* a custom init method, and invoking the necessary callback(s) if it does.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the merged bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @throws Throwable if thrown by init methods or by the invocation process
* @see #invokeCustomInitMethod
*/
//给一个bean一个机会去反应现在它的所有属性都设置好了,以及了解其所属的bean工厂(此对象)的机会。
//这意味着检查bean是实现了InitializingBean还是定义了它,一个自定义的init方法,并调用必要的回调(s),如果它这样做。
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
//调用InitializingBean的afterPropertiesSet()方法
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null) {
//返回初始化方法的名字(Init方法)
String initMethodName = mbd.getInitMethodName();
//如果有就执行
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
内部代码块16:
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
内部代码块17:
/**
* Return the (raw) singleton object registered under the given name.
* <p>Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
//返回在给定名称下注册的(原始)单例对象。检查已经实例化的单例,并允许早引用当前创建的单例(解析循环引用)。
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();
//Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);
//早期单例对象的缓存:bean名称——> bean实例
this.earlySingletonObjects.put(beanName, singletonObject);
//Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);
//单例工厂的缓存:bean名——> ObjectFactory
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
内部代码块18:
/**
* Add the given bean to the list of disposable beans in this factory,
* registering its DisposableBean interface and/or the given destroy method
* to be called on factory shutdown (if applicable). Only applies to singletons.
* @param beanName the name of the bean
* @param bean the bean instance
* @param mbd the bean definition for the bean
* @see RootBeanDefinition#isSingleton
* @see RootBeanDefinition#getDependsOn
* @see #registerDisposableBean
* @see #registerDependentBean
*/
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
// A bean with a custom scope...
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}
代码块10:getObjectForBeanInstance(sharedInstance, name, beanName, mbd)
见上面的代码块2:getObjectForBeanInstance
代码块11:mbd.isPrototype()
AbstractBeanDefinition.class
/**
* Return whether this a <b>Prototype</b>, with an independent instance
* returned for each call.
* @see #SCOPE_PROTOTYPE
*/
@Override
public boolean isPrototype() {
return SCOPE_PROTOTYPE.equals(scope);
}