ClassPathXmlApplicationContext加载配置过程

原创 2018年04月17日 16:51:49

spring加载基本的xml配置

最简单的xml配置,并使用ClassPathXmlApplicationContext加载

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
       <bean class="com.forcht.test.SimpleBean"/>
</beans>
 public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        SimpleBean simpleBean = applicationContext.getBean(SimpleBean.class);
        simpleBean.send();
    }

查看ClassPathXmlApplicationContext的继承关系
这里写图片描述
通过断点debug跟踪源码
ClassPathXmlApplicationContext构造器源码,不断调用父类的构造器直到AbstractApplicationContext

public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
        this(new String[] {configLocation}, true, null);
    }

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
            throws BeansException {

        super(parent);
        setConfigLocations(configLocations);
        if (refresh) {
            refresh();
        }
    }

查看AbstractApplicationContext构造器源码

public AbstractApplicationContext(ApplicationContext parent) {
        this();
        setParent(parent);
    }
public AbstractApplicationContext() {
        this.resourcePatternResolver = getResourcePatternResolver();
    }
//该方法创建一个资源处理器
protected ResourcePatternResolver getResourcePatternResolver() {
        return new PathMatchingResourcePatternResolver(this);
    }

到目前为止,ClassPathXmlApplicationContext已经有了两个资源加载器(一个由AbstractApplicationContext继承DefaultResourceLoader而来,一个是AbstractApplicationContext主动创建的PathMatchingResourcePatternResolver)
DefaultResourceLoader只能加载一个特定类路径的资源,PathMatchingResourcePatternResolver可以根据Ant风格加载多个资源。

每个父类的构造方法返回后调用AbstractRefreshableConfigApplicationContext的setConfigLocations(configLocations)方法

此方法的目的在于将占位符(placeholder)解析成实际的地址

public void setConfigLocations(String... locations) {
        if (locations != null) {
            Assert.noNullElements(locations, "Config locations must not be 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;
        }
    }
protected String resolvePath(String path) {
        return getEnvironment().resolveRequiredPlaceholders(path);
    }

getEnvironment()方法是由ConfigurableApplicationContext接口定义,在AbstractApplicationContext实现,其实就是判断environment 是否为空,不为空就创建一个StandardEnvironment

@Override
    public ConfigurableEnvironment getEnvironment() {
        if (this.environment == null) {
            this.environment = createEnvironment();
        }
        return this.environment;
    }
    protected ConfigurableEnvironment createEnvironment() {
        return new StandardEnvironment();
    }

Spring bean解析就在refresh方法,Spring所有的初始化都在这个方法中完成,该方法在AbstractApplicationContext实现

@Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();

            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // Prepare the bean factory for use in this context.
            prepareBeanFactory(beanFactory);

            try {
                // Allows post-processing of the bean factory in context subclasses.
                postProcessBeanFactory(beanFactory);

                // Invoke factory processors registered as beans in the context.
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);

                // Initialize message source for this context.
                initMessageSource();

                // Initialize event multicaster for this context.
                initApplicationEventMulticaster();

                // Initialize other special beans in specific context subclasses.
                onRefresh();

                // Check for listener beans and register them.
                registerListeners();

                // Instantiate all remaining (non-lazy-init) singletons.
                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish corresponding event.
                finishRefresh();
            }

            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                resetCommonCaches();
            }
        }
    }

//fresh准备工作,包括设置启动时间,是否激活标识位,初始化属性源(property source)配置

protected void prepareRefresh() {
        this.startupDate = System.currentTimeMillis();
        this.closed.set(false);
        this.active.set(true);

        if (logger.isInfoEnabled()) {
            logger.info("Refreshing " + this);
        }

        // Initialize any placeholder property sources in the context environment
        //该方法是空方法
        initPropertySources();

        // Validate that all properties marked as required are resolvable
        // see ConfigurablePropertyResolver#setRequiredProperties
        //属性校验
        getEnvironment().validateRequiredProperties();

        // Allow for the collection of early ApplicationEvents,
        // to be published once the multicaster is available...
        this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
    }

创建beanFactory
调用AbstractApplicationContext的obtainFreshBeanFactory方法获取obtainFreshBeanFactory

    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    //该方法在AbstractRefreshableApplicationContext实现
        refreshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    }

refreshBeanFactory方法

@Override
    protected final void refreshBeanFactory() throws BeansException {        
    //如果已经存在的BeanFactory则销毁
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
        //创建一个DefaultListableBeanFactory 
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            //定制beanFactory,由AbstractRefreshableApplicationContext实现
            customizeBeanFactory(beanFactory);
            //加载bean,由AbstractXmlApplicationContext实现
            loadBeanDefinitions(beanFactory);
            synchronized (this.beanFactoryMonitor) {
                this.beanFactory = beanFactory;
            }
        }
        catch (IOException ex) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
        }
    }

定制bean,customizeBeanFactory方法实现

protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
        if (this.allowBeanDefinitionOverriding != null) {
            beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
        }
        if (this.allowCircularReferences != null) {
            beanFactory.setAllowCircularReferences(this.allowCircularReferences);
        }
    }

加载bean

@Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        // Configure the bean definition reader with this context's
        // 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.
        initBeanDefinitionReader(beanDefinitionReader);
        loadBeanDefinitions(beanDefinitionReader);
    }
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lalalahaitang/article/details/79973288

使用Spring中的ClassPathXmlApplicationContext加载配置文件

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"...
  • wjq_15387296333
  • wjq_15387296333
  • 2017-06-02 14:56:39
  • 234

ClassPathXmlApplicationContext加载多个XML文件

用如下数组的形式就可以了。 public static void main(String[] args) throws IOException {       ApplicationContext...
  • gxlstone
  • gxlstone
  • 2013-12-31 13:56:56
  • 4544

由ClassPathXmlApplicationContext加载的classpath是哪里引发的思考

由ClassPathXmlApplicationContext加载的classpath引发的思考
  • iaiti
  • iaiti
  • 2016-09-20 17:57:29
  • 15096

spring学习笔记(3)——配置文件applicationContext.xml的加载

转载: http://blog.csdn.net/mezheng/article/details/73229811、把applicationContext.xml直接放在WEB-INF下,sprin...
  • xxxknight
  • xxxknight
  • 2015-06-28 14:40:48
  • 2262

java中读取配置文件的方法fileSystemXmlapplicationContext与classPathXmlApplicationContext

一、使用org.apache.commons.configuration 需要使用的是jar包:commons-collections-3.2.1.jar、commons-configuration-...
  • csdnliuxin123524
  • csdnliuxin123524
  • 2017-11-03 21:43:43
  • 429

ClassPathXmlApplicationContext无法加载XML

原因:ClassPathXmlApplicationContext 只能加载classes下的XML文件 解决方法:把存在XML的文件夹加入到 classpath  or resources 链接参见...
  • xiaxin_xx
  • xiaxin_xx
  • 2015-06-12 09:00:17
  • 734

ApplicationContext.xml中加载properties配置文件

在Maven项目中,该配置文件在/src/main/resources/下 之后比如配置数据库连接,方言等,可以直接用EL表达式来配置 eg: 数据源配置...
  • Mooner_guo
  • Mooner_guo
  • 2014-12-18 21:39:26
  • 3518

IDEA 中读取不了配置文件以及ClassPathXmlApplicationContext与FileSystemXmlApplicationContext

在学习Spring的时候(看的《Spring4.x企业应用开发实战》),书上用的IDE 是 Myeclipse,这里用的是IDEA。在编译:String configPath = "com/baoba...
  • llwwlql
  • llwwlql
  • 2017-07-04 16:36:46
  • 1552

Spring IOC 源码-ClassPathXmlApplicationContext-bean解析

1、使用方式-使用ApplicationContext方式加载XML @Test     public void testBeanLoader(){         BeanFactory bf = ...
  • xiaoxiaoxuanao
  • xiaoxiaoxuanao
  • 2016-09-18 13:58:47
  • 407
收藏助手
不良信息举报
您举报文章:ClassPathXmlApplicationContext加载配置过程
举报原因:
原因补充:

(最多只允许输入30个字)