Spring 加载多个xml配置文件的原理分析

目录
  • 示例
    • spring-configlication.xml:
    • spring-config-instance-factory.xml
    • java示例代码
  • 实现
    • AbstractRefreshableConfigApplicationContext
    • AbstractApplicationContext
    • AbstractRefreshableApplicationContext
    • AbstractXmlApplicationContext

示例

先给出两个Bean的配置文件:

spring-configlication.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="person" class="com.john.aop.Person">
    </bean>
    <bean id="ChineseFemaleSinger" class="com.john.beanFactory.Singer" abstract="true" >
        <property name="country" value="中国"/>
        <property name="gender" value="女"/>
    </bean>

</beans>

spring-config-instance-factory.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="carFactory" class="com.john.domain.CarFactory" />
    <!--实例工厂方法创建bean-->
    <bean id="instanceCar" factory-bean="carFactory" factory-method="createCar">
        <constructor-arg ref="brand"/>
    </bean>
    <bean id="brand" class="com.john.domain.Brand" />
</beans>

java示例代码

public class ConfigLocationsDemo {

    public static void main(String[] args) {

        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();
        applicationContext.setConfigLocations("spring-configlocation.xml","spring-config-instance-factory.xml");
        applicationContext.refresh();
         String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }
}

这样我们就会在控制台打印出两个配置文件中所有的Bean.

person
ChineseFemaleSinger
carFactory
instanceCar
brand

Process finished with exit code 0

实现

AbstractRefreshableConfigApplicationContext

从类的名字推导出这是一个带刷新功能并且带配置功能的应用上下文。

/**
     * Set the config locations for this application context.
     * <p>If not set, the implementation may use a default as appropriate.
     */
    public void setConfigLocations(@Nullable String... locations) {
        if (locations != null) {

            this.configLocations = new String[locations.length];
            for (int i = 0; i < locations.length; i++) {
                this.configLocations[i] = resolvePath(locations[i]).trim();
            }
        }
        else {
            this.configLocations = null;
        }
    }

这个方法很好理解,首先根据传入配置文件路径字符串数组遍历,并且里面调用了resolvePath方法解析占位符。那么我们要想下了,这里只做了解析占位符并且把字符串赋值给configLocations变量,那必然肯定会在什么时候去读取这个路径下的文件并加载bean吧?会不会是在应用上下文调用refresh方法的时候去加载呢?带着思考我们来到了应用上下文的refresh方法。

AbstractApplicationContext

     @Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {

            // Tell the subclass to refresh the internal bean factory.
            //告诉子类刷新 内部BeanFactory
            //https://www.iteye.com/blog/rkdu2-163-com-2003638
            //内部会加载bean定义
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      }
    }

    /**
     * Tell the subclass to refresh the internal bean factory.
     * @return the fresh BeanFactory instance
     * @see #refreshBeanFactory()
     * @see #getBeanFactory()
     */
    //得到刷新过的beanFactory
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        //抽象类AbstractRefreshableApplicationContext
        //里面会加载bean定义
        //todo 加载bean定义
        refreshBeanFactory();
        //如果beanFactory为null 会报错
        return getBeanFactory();
    }

    /**
     * Subclasses must implement this method to perform the actual configuration load.
     * The method is invoked by {@link #refresh()} before any other initialization work.
     * <p>A subclass will either create a new bean factory and hold a reference to it,
     * or return a single BeanFactory instance that it holds. In the latter case, it will
     * usually throw an IllegalStateException if refreshing the context more than once.
     * @throws BeansException if initialization of the bean factory failed
     * @throws IllegalStateException if already initialized and multiple refresh
     * attempts are not supported
     */
    //AbstractRefreshableApplicationContext 实现了此方法
    //GenericApplicationContext 实现了此方法
    protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;

我们看到refreshBeanFactory的第一句注释就提到了Subclasses must implement this method to perform the actual configuration load,意思就是子类必须实现此方法来完成最终的配置加载,那实现此方法的Spring内部默认有两个类,AbstractRefreshableApplicationContext和GenericApplicationContext,这里我们就关心AbstractRefreshableApplicationContext:

AbstractRefreshableApplicationContext

我们要时刻记得上面的AbstractRefreshableConfigApplicationContext类是继承于AbstractRefreshableApplicationContext的,到这里我们给张类关系图以便加深理解:

/**
     * This implementation performs an actual refresh of this context's underlying
     * bean factory, shutting down the previous bean factory (if any) and
     * initializing a fresh bean factory for the next phase of the context's lifecycle.
     */
    @Override
    protected final void refreshBeanFactory() throws BeansException {

         //判断beanFactory 是否为空
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory(); //设置beanFactory = null
        }
        try {
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            //加载Bean定义
            //todo AbstractXmlApplicationContext 子类实现 放入beandefinitionMap中
            loadBeanDefinitions(beanFactory);
        }
        catch (IOException ex) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
        }
    }

这里就看到了前篇文章提到一个很重要的方法loadBeanDefinitions,我们再拿出来回顾下加深理解:

/**
     * Load bean definitions into the given bean factory, typically through
     * delegating to one or more bean definition readers.
     * @param beanFactory the bean factory to load bean definitions into
     * @throws BeansException if parsing of the bean definitions failed
     * @throws IOException if loading of bean definition files failed
     * @see org.springframework.beans.factory.support.PropertiesBeanDefinitionReader
     * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
     */
    protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
            throws BeansException, IOException;

这里因为我们是采用xml配置的,那么肯定是XmlBeanDefinitionReader无疑,我们再回顾下实现此方法的AbstractXmlApplicationContext:

AbstractXmlApplicationContext

/**
     * Loads the bean definitions via an XmlBeanDefinitionReader.
     * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
     * @see #initBeanDefinitionReader
     * @see #loadBeanDefinitions
     */
    //todo 重载了 AbstractRefreshableApplicationContext
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        //忽略代码。。
        loadBeanDefinitions(beanDefinitionReader);
    }

    /**
     * Load the bean definitions with the given XmlBeanDefinitionReader.
     * <p>The lifecycle of the bean factory is handled by the {@link #refreshBeanFactory}
     * method; hence this method is just supposed to load and/or register bean definitions.
     * @param reader the XmlBeanDefinitionReader to use
     * @throws BeansException in case of bean registration errors
     * @throws IOException if the required XML document isn't found
     * @see #refreshBeanFactory
     * @see #getConfigLocations
     * @see #getResources
     * @see #getResourcePatternResolver
     */
    //bean工厂的生命周期由 refreshBeanFactory 方法来处理
    //这个方法只是 去加载和注册 bean定义
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
        //ClassPathXmlApplicationContext
        Resource[] configResources = getConfigResources();
        if (configResources != null) {
            reader.loadBeanDefinitions(configResources);
        }
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            //抽象AbstractBeanDefinitionReader里去加载
            reader.loadBeanDefinitions(configLocations);
        }
    }

这里我们终于到了这个configLocations的用武之地,它就传入了XmlBeanDefinitionReader的loadBeanDefinitions方法中。在这里我们也看到了Spring首先会根据configResources加载BeanDefinition,其次才会去根据configLocations配置去加载BeanDefinition。到这里我们可以学到Spring中对面向对象中封装,继承和多态的运用。下篇文章我们继续剖析Spring关于Xml加载Bean定义的点滴。

以上就是Spring 加载多个xml配置文件的原理分析的详细内容,更多关于Spring 加载xml配置文件的资料请关注我们其它相关文章!

(0)

相关推荐

  • Spring根据XML配置文件 p名称空间注入属性的实例

    要生成对象并通过名称空间注入属性的类 代码如下: package com.swift; public class User { private String userName; public void setUserName(String userName) { this.userName = userName; } public String fun() { return "User's fun is ready."+this.userName; } } XML配置文件写法如下: &

  • Spring手动生成web.xml配置文件过程详解

    步骤一: 找到自己所创建的项目名,效果如下: 步骤二: 右击自己所创建的项目---->Java EE Tools---->点击Generate Deployment Descriptor Stub,完成这几步,即可,效果如下: 最后,就会生成web.xml配置文件会在WebContent-->WEB-INF文件中,如下: 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们.

  • spring如何实现两个xml配置文件间的互调

    这篇文章主要介绍了spring如何实现两个xml配置文件间的互调,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 首先建两个测试类 package soundsystem; public class Dog { private String Cry; private Cat Cat; public void setCry(String cry) { Cry = cry; } public void setCat(soundsystem.Cat c

  • Spring 配置文件XML头部文件模板实例详解

    普通spring配置文件模板: <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.s

  • Spring boot AOP通过XML配置文件声明

    通过 XML 配置文件声明 在前两篇博文和示例中,我们已经展示了如何通过注解配置去声明切面,下面我们看看如何在 XML 文件中声明切面.下面先列出 XML 中声明 AOP 的常用元素: AOP配置元素 用途 aop:advisor 定义AOP通知器 aop:after 定义AOP后置通知(不管被通知的方法是否执行成功) aop:after-returning 定义AOP返回通知 aop:after-throwing 定义AOP异常通知 aop:around 定义AOP环绕通知 aop:aspec

  • Spring根据XML配置文件注入属性的方法

    方法一使用setter方法 package com.swift; public class Book { private String bookName; public void setBook(String bookName) { this.bookName = bookName; } @Override public String toString() { return "Book [book=" + bookName + "]"; } } 在Spring框架中

  • spring是如何解析xml配置文件中的占位符

    前言 我们在配置Spring Xml配置文件的时候,可以在文件路径字符串中加入 ${} 占位符,Spring会自动帮我们解析占位符,这么神奇的操作Spring是怎么帮我们完成的呢?这篇文章我们就来一步步揭秘. 1.示例 ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(); applicationContext.setConfigLocation("${java.versi

  • 详解spring applicationContext.xml 配置文件

    applicationContext.xml 文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http

  • spring web.xml指定配置文件过程解析

    这篇文章主要介绍了spring web.xml指定配置文件过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-beans.xml</param-value> </context-param> 指定

  • spring*.xml配置文件明文加密的实现

    说明:客户要求spring*.xml中Oracle/Redis/MongoDB的IP.端口.用户名.密码不能明文存放,接到需求的我,很无奈,但是还是的硬着头皮搞 系统架构:spring+mvc(Oracle是用jdbc自己封装的接口) 1.数据库配置文件加密 原xml配置 <?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/

  • 如何在spring官网查找XML基础配置文件

    这篇文章主要介绍了如何在spring官网查找XML基础配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.首先进入spring官网:https://spring.io/: 2.然后点击projects目录,出现如下页面: 3.点击spring framework进入spring框架页面,点击Learn,点击Reference Doc如图: 4.进入doc页面后,点击Core,如图: 5.进入core页面后,点击1.2.1 Configu

  • Spring主配置文件(applicationContext.xml) 导入约束详解

    eclipse导入Spring配置文件约束  Windows-Preference-XML-XMLCatalog 点 Add 选File System 下spring的解压包下的schema文件夹,选beans,然后选择spring对应的版本的xsd文件 选择指定xsd文件,再Key的路径后面添加"/spring-beans-4.2.xsd"点ok 创建applicationContext.xml   写根元素 <beans></beans> Add导入XSI,

随机推荐