spring创建bean源码

一:doGetBean方法

1.判断beanName是否为空,为空抛异常,再判断beanName是否以&开头是的话去掉&。

2.执行getSingleton(beanName),获取bean的登记式单例,如果需要的单例不为空的话返回已存在的单例。(返回语句在方法结尾处)

if ((sharedInstance != null) && (args == null)) {
            if (this.logger.isDebugEnabled()) {
                  if (isSingletonCurrentlyInCreation(beanName)) {
                      this.logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
                  }
                  else{
                      this.logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
                  }
            }
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}

3.如果beanDefination中不存在指定bean的beanDefination并且父级容器不为空则去父级容器中请求bean

if ((parentBeanFactory != null) && (!containsBeanDefinition(beanName)))
{
    String nameToLookup = originalBeanName(name);
    if (args != null)
    {
        return parentBeanFactory.getBean(nameToLookup, args);
    }

    return parentBeanFactory.getBean(nameToLookup, requiredType);
}

4.获取当前请求的bean所依赖的所有bean名称,不为空的话去递归调用getBean方法

String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
    for (int i = 0; i < dependsOn.length; i++) {
        String dependsOnBean = dependsOn[i];
        getBean(dependsOnBean);
        registerDependentBean(dependsOnBean, beanName);
    }

}
上一篇:Spring框架参考手册(4.2.6版本)翻译——第三部分 核心技术 6.8.3 使用FactoryBean自定义实例化逻辑


下一篇:TextView 文字拼接