ClassPathXmlApplicationContext加载配置过程

spring加载基本的xml配置

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


<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的继承关系
ClassPathXmlApplicationContext加载配置过程_第1张图片
通过断点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();
    }

创建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);
    }

你可能感兴趣的:(spring)