Spring-IoC原理

621 阅读17分钟

概念

IoC(Inversion of Control,控制反转)

IOC-即控制反转,是一种设计思想,帮助我们设计出松耦合的程序。spring的IOC容器作为IOC设计思想的实现,是spring的核心,该容器负责控制对象的生命周期和对象间的依赖关系。关于控制反转如何理解:

  • 谁控制谁,控制什么:传统java程序设计,直接在对象内部通过new创建对象,程序主动创建依赖对象;IOC设计思想,则是由IOC容器来创建对象;所以是IOC容器控制了对象,具体控制了外部资源的获取
  • 什么是反转,反转了什么:传统程序的主动创建依赖对象,可以理解为正转;反转则是由IoC容器来帮助创建依赖对象,是被动的接受依赖对象

DI(Dependency Injection,依赖注入)

DI-依赖注入,这个概念和IoC经常同时出现,其实他们是同一个概念的不同角度描述。由于IoC的概念比较模糊,所以2004年大师级人物Martin Fowler又给出了一个新的名字:“依赖注入”,相对IoC 而言,“依赖注入”明确描述了“被注入对象依赖IoC容器配置依赖对象”。具体可以参考这篇原作《Inversion of Control Containers and the Dependency Injection pattern》
依赖注入—是组件之间依赖关系由容器在运行期决定,形象的说,即由容器动态的将某个依赖关系注入到组件之中。通过依赖注入机制,我们只需要通过简单的配置,而无需任何代码就可指定目标需要的资源,完成自身的业务逻辑,而不需要关心具体的资源来自何处,由谁实现。

架构

上图是spring框架的整体架构,从架构图我们可以看出来spring的根基就是core container,就是我们说的IOC容器。在此基础上才有AOP,DATA和WEB的繁荣,而core container的核心就是bean、context、core三个jar包。其中bean是spring的基石,容器控制的对象都是以bean形式存在,context则提供了应用的上下文环境。

BeanFactory和ApplicationContext

org.springframework.beans和org.springframework.contex是spring框架IoC的基础,其中org.springframework.beans.factory.BeanFactory是spring框架的核心接口,提供了高级IoC配置机制,BeanFactory使管理不同类型的Java对象成为可能。org.springframework.contex.ApplicationContext接口继承自BeanFactory,提供了更多面向应用的功能,融合了spring的AOP特性,提供了国际化支持以及框架事件体系等。简单区分二者,BeanFactory是spring框架基础设施,面向spring本身;ApplicationContext则是面向spring框架的开发者,几乎所有应用场合都可以直接使用ApplicationContext。

BeanFactory

以DefaultListableBeanFactory为例如下图所示,包含了最核心的BeanDefinitionRegistry和BeanFactory,也就是bean的定义和生产bean的工厂。

ApplicationContext

以ClassPathXmlApplicationContext为例如下图所示,可以看到ApplicationConext继承类资源,消息,事件,环境,工厂五种能力。

源码分析

以ClassPathXmlApplicationContext为例进行分析,该类的构造函数如下所示,传入配置文件路径参数

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)throws BeansException {
	super(parent);
	setConfigLocations(configLocations);
	if (refresh) {
	    // 核心方法
		refresh();
	}
}

其中refresh方法中记录了IoC容器初始化整个流程

  /**
  * Load or refresh the persistent representation of the configuration
  */
public void refresh() throws BeansException, IllegalStateException {
    //容器重启同步监控锁,防止刷新进行到一半被重复执行
    synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        // 填充配置文件占位符,记录容器启动时间和启动状态
        prepareRefresh();
        // 完成配置文件定义到注册表登记bean的流程,此时对象还未被创建
        // Tell the subclass to refresh the internal bean factory.
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
        // Prepare the bean factory for use in this context.
        // 配置类加载器,定制特殊bean,添加BeanPostProcessor可供回调
        prepareBeanFactory(beanFactory);

        try {
            // Allows post-processing of the bean factory in context subclasses.
            //工厂加载完配置,初始化之前回调PostProcessBeanFactory,作为工厂扩展功能
            postProcessBeanFactory(beanFactory);
            // Invoke factory processors registered as beans in the context.
            //调用上文注册的扩展接口PostProcessBeanFactory的实现,为扩展接口为列表类型
            invokeBeanFactoryPostProcessors(beanFactory);
            // Register bean processors that intercept bean creation.
            // bean扩展:postProcessBeforeInitialization和postProcessAfterInitialization
            //分别在Bean初始化之前和初始化之后得到执行
            registerBeanPostProcessors(beanFactory);
            // Initialize message source for this context.
            //初始化MessageSource对象,国际化
            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();
            // Instantiate all remaining (non-lazy-init) singletons.
            // 实例化工厂注册表里面的bean(懒加载的除外,用到才实例化)
            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;
        }
        finally {
            // Reset common introspection caches in Spring's core, since we
            // might not ever need metadata for singleton beans anymore...
            resetCommonCaches();
        }
    }
}

创建BeanFactory

refresh初始化过程中,完成第一步prepareRefresh(填充配置文件占位符,记录容器启动时间和启动状态)后,进入IoC初始化最关键的一步BeanFactory的创建:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    //创建新beanFactory,销毁旧的
    refreshBeanFactory();
    //返回创建的新工厂
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (logger.isDebugEnabled()) {
        logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
    }
    return beanFactory;
}

refreshBeanFactory流程

protected final void refreshBeanFactory() throws BeansException {
    //判断是否有this.beanFactory存在,存在则清除map中存在的对象,同时置this.beanFactory为null
    if (hasBeanFactory()) {
        destroyBeans();
        closeBeanFactory();
    }
    try {
        //返回新建的DefaultListableBeanFactory
        DefaultListableBeanFactory beanFactory = createBeanFactory();
        //工厂标识id
        beanFactory.setSerializationId(getId());
        //设置容器是否允许对象覆盖,循环依赖
        customizeBeanFactory(beanFactory);
        //加载bean定义
        loadBeanDefinitions(beanFactory);
        synchronized (this.beanFactoryMonitor) {
            this.beanFactory = beanFactory;
        }
    }
    catch (IOException ex) {
        throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
    }
}

createBeanFactory构造出子类对象DefaultListableBeanFactory,涵盖了工厂BeanFactory,对象定义BeanDefinition,和注册表AliasRegistry的能力,是一个完整的对象工厂。后续就是使用该工厂能力将配置文件信息转化为bean定义,再进行对象创建和属性赋值。

配置文件读取

接上面分析,创建出DefaultListableBeanFactory后,需要利用该工厂能力将配置文件转化为对应的bean对象。

  • 实例化资源阅读器,开启资源加载
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    // Create a new XmlBeanDefinitionReader for the given BeanFactory.
    // 实例化一个工厂类的XML文件阅读器
    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

    // Configure the bean definition reader with this context
    // resource loading environment.
    beanDefinitionReader.setEnvironment(this.getEnvironment());
    beanDefinitionReader.setResourceLoader(this);
    beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

    // Allow a subclass to provide custom initialization of the reader,
    // then proceed with actually loading the bean definitions.
    // 开启xml文件校验
    initBeanDefinitionReader(beanDefinitionReader);
    // beanDefinitionReader阅读器加载资源文件
    loadBeanDefinitions(beanDefinitionReader);
}
  • 加载资源文件
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
    // 针对ClassPathXmlApplicationContext返回的是构造函数中资源配置路径
    Resource[] configResources = getConfigResources();
    if (configResources != null) {
        // 循环加载所有配置文件
        reader.loadBeanDefinitions(configResources);
    }
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
        reader.loadBeanDefinitions(configLocations);
    }
}
  • 循环加载所有配置文件
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
    Assert.notNull(resources, "Resource array must not be null");
    int counter = 0;
    for (Resource resource : resources) {
        counter += loadBeanDefinitions(resource);
    }
    return counter;
}
  • 获取路径,读取资源配置文件
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
    return loadBeanDefinitions(new EncodedResource(resource));
}
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
    Assert.notNull(encodedResource, "EncodedResource must not be null");
    if (logger.isInfoEnabled()) {
        logger.info("Loading XML bean definitions from " + encodedResource.getResource());
    }
       //使用ThreadLocal存放配置文件路径
    Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
    if (currentResources == null) {
        currentResources = new HashSet<EncodedResource>(4);
        this.resourcesCurrentlyBeingLoaded.set(currentResources);
    }
    if (!currentResources.add(encodedResource)) {
        throw new BeanDefinitionStoreException(
                "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
    }
    try {
        InputStream inputStream = encodedResource.getResource().getInputStream();
        try {
            InputSource inputSource = new InputSource(inputStream);
            if (encodedResource.getEncoding() != null) {
                inputSource.setEncoding(encodedResource.getEncoding());
            }
               //真正解析资源配置文件
            return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
        }
        finally {
            inputStream.close();
        }
    }
    catch (IOException ex) {
        throw new BeanDefinitionStoreException(
                "IOException parsing XML document from " + encodedResource.getResource(), ex);
    }
    finally {
        currentResources.remove(encodedResource);
        if (currentResources.isEmpty()) {
            this.resourcesCurrentlyBeingLoaded.remove();
        }
    }
}
  • 配置文件解析
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) {
    try {
        //xml文件生成Document对象
        Document doc = doLoadDocument(inputSource, resource);
        //bean对象注册
        return registerBeanDefinitions(doc, resource);
    }
    // 后续各种catch代码省略
}

对象注册

接上一节,完成了xml到Document的转化,调用registerBeanDefinitions进行对象的注册。

  • document阅读器生成,开启document注册流程
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
    //生成document对象阅读器
    BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
    //注册表已存在Definition数量(对象的描述)
    int countBefore = getRegistry().getBeanDefinitionCount();
    //将doc树的bean定义注册到工厂类的注册表属性
    documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
    return getRegistry().getBeanDefinitionCount() - countBefore;
}
  • 遍历document逐个解析xml标签
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
    this.readerContext = readerContext;
    logger.debug("Loading bean definitions");
    Element root = doc.getDocumentElement();
    doRegisterBeanDefinitions(root);
}
protected void doRegisterBeanDefinitions(Element root) {
    //创建解析DOM树对象的工具BeanDefinitionParserDelegate
    this.delegate = createDelegate(getReaderContext(), root, parent);
    if (this.delegate.isDefaultNamespace(root)) {
        String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
        //关于profile标签的操作
        if (StringUtils.hasText(profileSpec)) {
            String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
                    profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
            if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
                if (logger.isInfoEnabled()) {
                    logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
                            "] not matching: " + getReaderContext().getResource());
                }
                return;
            }
        }
    }
    preProcessXml(root);//预留方法,解析前的扩展操作
    parseBeanDefinitions(root, this.delegate);//核心方法,解析DOM树
    postProcessXml(root);//预留方法,解析后的扩展操作
    this.delegate = parent;
}

配置文件标签解析

spring中标签包括默认标签和自定义标签,后续主要分析默认标签解析过程。接上一节parseBeanDefinitions对document中的标签进行解析。

  • 解析dom文件树
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
    if (delegate.isDefaultNamespace(root)) {
        NodeList nl = root.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node instanceof Element) {
                Element ele = (Element) node;
                //包含http://www.springframework.org/schema/beans的为默认命名空间
                if (delegate.isDefaultNamespace(ele)) {
                    parseDefaultElement(ele, delegate);
                }
                else {
                    //非默认命名空间的有<mvc/>、<context/>、<aop/>等
                    delegate.parseCustomElement(ele);
                }
            }
        }
    }
    else {
        delegate.parseCustomElement(root);
    }
}
  • 默认标签解析
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
    if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
        importBeanDefinitionResource(ele);
    }
    else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
        processAliasRegistration(ele);
    }
    else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
        processBeanDefinition(ele, delegate);//解析命名空间为bean的标签
    }
    else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
        // recurse
        doRegisterBeanDefinitions(ele);
    }
}

上述代码逻辑比较清晰,对4中不同的标签(import、alias、bena和benas)做了不同处理,具体代码不展开分析。最终带有bean标签会被映射到BeanDefinitionHolder对象里面,接下来是把BeanDefinition对象登记到工厂的注册表里面。

  • BeanDefinitionHolder转化
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			// 完成bean转化后触发注册事件
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}
  • 注册BeanDefinition对象
public static void registerBeanDefinition(
        BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
        throws BeanDefinitionStoreException {
    // Register bean definition under primary name.
    String beanName = definitionHolder.getBeanName();
    //通过beanName注册definitionHolder的BeanDefinition对象到注册表
    registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
    // Register aliases for bean name, if any.
    //如果有别名也一并注册
    String[] aliases = definitionHolder.getAliases();
    if (aliases != null) {
        for (String alias : aliases) {
            registry.registerAlias(beanName, alias);
        }
    }
}

具体调用DefaultListableBeanFactory中的registerBeanDefinition方法进行注册

public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
        throws BeanDefinitionStoreException {

    Assert.hasText(beanName, "Bean name must not be empty");
    Assert.notNull(beanDefinition, "BeanDefinition must not be null");

    if (beanDefinition instanceof AbstractBeanDefinition) {
        try {
            ((AbstractBeanDefinition) beanDefinition).validate();
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                    "Validation of bean definition failed", ex);
        }
    }

    BeanDefinition oldBeanDefinition;
    oldBeanDefinition = this.beanDefinitionMap.get(beanName);
    //新的xml获取出来的应该为空
    if (oldBeanDefinition != null) {
        if (!isAllowBeanDefinitionOverriding()) {
            throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                    "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
                    "': There is already [" + oldBeanDefinition + "] bound.");
        }
        else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
            // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
            if (this.logger.isWarnEnabled()) {
                this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +
                        "' with a framework-generated bean definition: replacing [" +
                        oldBeanDefinition + "] with [" + beanDefinition + "]");
            }
        }
        else if (!beanDefinition.equals(oldBeanDefinition)) {
            if (this.logger.isInfoEnabled()) {
                this.logger.info("Overriding bean definition for bean '" + beanName +
                        "' with a different definition: replacing [" + oldBeanDefinition +
                        "] with [" + beanDefinition + "]");
            }
        }
        else {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Overriding bean definition for bean '" + beanName +
                        "' with an equivalent definition: replacing [" + oldBeanDefinition +
                        "] with [" + beanDefinition + "]");
            }
        }
        this.beanDefinitionMap.put(beanName, beanDefinition);
    }
    else {
        //初始化的过程,不允许实例化
        if (hasBeanCreationStarted()) {
            // Cannot modify startup-time collection elements anymore (for stable iteration)
            synchronized (this.beanDefinitionMap) {
                this.beanDefinitionMap.put(beanName, beanDefinition);
                List<String> updatedDefinitions = new ArrayList<String>(this.beanDefinitionNames.size() + 1);
                updatedDefinitions.addAll(this.beanDefinitionNames);
                updatedDefinitions.add(beanName);
                this.beanDefinitionNames = updatedDefinitions;
                if (this.manualSingletonNames.contains(beanName)) {
                    Set<String> updatedSingletons = new LinkedHashSet<String>(this.manualSingletonNames);
                    updatedSingletons.remove(beanName);
                    this.manualSingletonNames = updatedSingletons;
                }
            }
        }
        else {
            //最核心的一步,就是beanDefinitionMap增加beanDefinition
            // Still in startup registration phase
            this.beanDefinitionMap.put(beanName, beanDefinition);
            this.beanDefinitionNames.add(beanName);
            this.manualSingletonNames.remove(beanName);
        }
        this.frozenBeanDefinitionNames = null;
    }
    if (oldBeanDefinition != null || containsSingleton(beanName)) {
        resetBeanDefinition(beanName);
    }
}

到这一步,已经完整的把所有xml配置文件里面定义的对象转化到BeanFactory里面的beanDefinitionMap。但是此时IOC容器还没开始实例化这些对象,接下来就是实例化的过程。回顾开头refresh()方法中的,finishBeanFactoryInitialization(beanFactory)步骤,该步骤就是完成对象实例化的过程。

对象实例化

  • 实例化入口
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));
    }

    // Register a default embedded value resolver if no bean post-processor
    // (such as a PropertyPlaceholderConfigurer bean) registered any before:
    // at this point, primarily for resolution in annotation attribute values.
    if (!beanFactory.hasEmbeddedValueResolver()) {
    	beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }

    // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
    //JVM动态织入第三方模块
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        // getBean提前让LoadTimeWeaverAware进行实例化
        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();
}
  • 单例对象预实例化
public void preInstantiateSingletons() throws BeansException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Pre-instantiating singletons in " + this);
    }
   
    List<String> 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()) {
            //如果为FactoryBean子类,先构造该类然后实例化它的商品类;反之,直接实例化该类
            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>() {
                        @Override
                        public Boolean run() {
                            return ((SmartFactoryBean<?>) factory).isEagerInit();
                        }
                    }, getAccessControlContext());
                }
                else {
                    isEagerInit = (factory instanceof SmartFactoryBean &&
                            ((SmartFactoryBean<?>) factory).isEagerInit());
                }
                if (isEagerInit) {
                    getBean(beanName);
                }
            }
            else {
                getBean(beanName);//进入实例化bean
            }
        }
    }
    // Trigger post-initialization callback for all applicable beans...
    // 触发所有bean的post-initialization回调
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    @Override
                    public Object run() {
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }
                }, getAccessControlContext());
            }
            else {
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}
  • 实例化对象

AbstractBeanFactory类中的getBean方法进行实例化对象

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

protected <T> T doGetBean(
        final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
        throws BeansException {
    // 转换BeanName(XML中别名、去掉FactoryBean的“&”)
    final String beanName = transformedBeanName(name);
    //返回的实例化对象,等待赋值
    Object bean;
    // 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);
    }

    else {
        //判断该beanName是否被实例化为prototype或者被创建中,如果是则抛异常
        // Fail if we're already creating this bean instance:
        // We're assumably within a circular reference.
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }

        //判断bean的定义是否存在工厂里面
        // Check if bean definition exists in this factory.
        BeanFactory parentBeanFactory = getParentBeanFactory();
        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) {
            markBeanAsCreated(beanName);
        }

        // 具体实例化过程
        try {
            // 获取bean的定义对象
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);
            // 优先实例化所要依赖的对象递归检查
            // Guarantee initialization of beans that the current bean depends on.
            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);
                    try {
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }

            //创建单例对象
            // Create bean instance.
            if (mbd.isSingleton()) {
                sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                    @Override
                    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);
            }

            //同理创建prototype类型的对象,非单例,创建出来后不再维护生命周期
            else if (mbd.isPrototype()) {
                // 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.
    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());
        }
    }
    return (T) bean;
}
  • 创建bean
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
 RootBeanDefinition mbdToUse = mbd;
  //确保对象对应的类被加载进内存
 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) {
 }
 try {
    // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
    // 为AOP做的钩子,如果Bean配置了PostProcessor,那么返回一个Proxy
    Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
    if (bean != null) {
       return bean;
    }
 }
 catch (Throwable ex) {
 }
 //真正的创建对象
 Object beanInstance = doCreateBean(beanName, mbdToUse, args);
 if (logger.isDebugEnabled()) {
    logger.debug("Finished creating instance of bean '" + beanName + "'");
 }
 return beanInstance;
}

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
    throws BeanCreationException {
 // Instantiate the bean.
 BeanWrapper instanceWrapper = null;
 if (mbd.isSingleton()) {
    //从工厂bean缓存容器里面移除
    instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
 }
 //为空说明不是工厂bean,可以直接创建对象
 if (instanceWrapper == null) {
     //这一步是真正的创建对象
    instanceWrapper = createBeanInstance(beanName, mbd, args);
 }
 final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
 Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
 mbd.resolvedTargetType = beanType;
 // Allow post-processors to modify the merged bean definition.
 //创建完bean后的一些特殊操作
 synchronized (mbd.postProcessingLock) {
    if (!mbd.postProcessed) {
       try {
          applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
       }
       catch (Throwable ex) {
          throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Post-processing of merged bean definition failed", ex);
       }
       mbd.postProcessed = true;
    }
 }
  //解析循环依赖的逻辑
 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
       isSingletonCurrentlyInCreation(beanName));
 if (earlySingletonExposure) {
    addSingletonFactory(beanName, new ObjectFactory<Object>() {
       @Override
       public Object getObject() throws BeansException {
          return getEarlyBeanReference(beanName, mbd, bean);
       }
    });
 }
 // Initialize the bean instance.
 Object exposedObject = bean;
 try {
    // 依赖注入,初始化属性值
    populateBean(beanName, mbd, instanceWrapper);
    if (exposedObject != null) {
       exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
 }
 catch (Throwable ex) {
 }
 if (earlySingletonExposure) {
    Object earlySingletonReference = getSingleton(beanName, false);
    if (earlySingletonReference != null) {
       if (exposedObject == bean) {
          exposedObject = earlySingletonReference;
       }
       else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
          String[] dependentBeans = getDependentBeans(beanName);
          Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
          for (String dependentBean : dependentBeans) {
             if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                actualDependentBeans.add(dependentBean);
             }
          }
          if (!actualDependentBeans.isEmpty()) {
       }
    }
 }
 // Register bean as disposable.
 try {
    registerDisposableBeanIfNecessary(beanName, bean, mbd);
 }
 catch (BeanDefinitionValidationException ex) {
    throw new BeanCreationException(
          mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
 }

 return exposedObject;
}
  • 真正bean实例化操作createBeanInstance
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)  {
    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.
 return instantiateBean(beanName, mbd);
}
  • 无参数构造方法实例化
@Override
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
 // Do not 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 {
                //构造方法反射实例化
                constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
             }
             bd.resolvedConstructorOrFactoryMethod = constructorToUse;
          }
          catch (Throwable ex) {
             throw new BeanInstantiationException(clazz, "No default constructor found", ex);
          }
       }
    }
    return BeanUtils.instantiateClass(constructorToUse);
 }
 else {
    // Must generate CGLIB subclass.
    return instantiateWithMethodInjection(bd, beanName, owner);
 }
}
  • 核心反射生成类
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
 Assert.notNull(ctor, "Constructor must not be null");
 try {
    ReflectionUtils.makeAccessible(ctor);
    //核心核心!终于重bean里面获取类,类的构造方法,然后反射new除了对象,好累。
    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());
 }
}
  • 对象属性初始化 完成对象创建以后,在createBean方法中通过populateBean方法进行属性的初始化
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
 //获取所有的属性值
 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.
 boolean continueWithPropertyPopulation = true;

 //出现BeanPostProcessors又是钩子,给出各种特殊操作
 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) {
        //通过name属性来装配
       autowireByName(beanName, mbd, bw, newPvs);
    }

    // Add property values based on autowire by type if applicable.
    if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
       //通过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);
    }
 }
 //实际装配配置文件的属性
 applyPropertyValues(beanName, mbd, bw, pvs);
}

最终,我们完成了从xml配置文件,到注册表注册,到实例化对象,以及最后的对象的初始化。整个过程我们只是粗略的分析,后续会有文章对其中一些难点和细节进行分析。

参考

  1. 跟着开涛学spring3
  2. The IoC container
  3. 源码解读Spring IOC原理