ClassPathXmlApplicationContext加载配置过程

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);
    }
  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Bean创建过程涉及到以下几个步骤:1. 定义Bean:在XML文件或注解中定义Bean;2. 加载配置:通过ClassPathXmlApplicationContext或AnnotationConfigApplicationContext加载Bean定义;3. 实例化Bean:使用反射机制实例化Bean;4. 注入依赖:将Bean定义中定义的依赖注入到Bean实例中;5. 返回Bean:返回Bean实例。 ### 回答2: Spring Bean创建过程主要包括以下几个步骤: 1. 配置文件读取:首先,Spring会读取配置文件,例如XML配置文件或者Java配置类,获取Bean的定义和依赖关系。 2. Bean定义解析:Spring将解析配置文件,根据Bean的定义创建和维护一个内部的Bean定义注册表。这个注册表记录了Bean的各种属性,如Bean的类名、作用域、构造函数参数、依赖关系等。 3. Bean实例化:根据Bean的定义,Spring会创建该Bean的一个实例。可以使用构造函数实例化Bean,也可以通过工厂方法或者Bean的后置处理器(BeanPostProcessor)进行实例化。 4. 依赖注入:如果Bean有依赖关系,Spring会自动将依赖的Bean注入到当前Bean中。注入方式可以是构造函数注入、setter方法注入或者接口注入。 5. Bean的初始化:如果Bean实现了InitializingBean接口,Spring会调用其初始化方法进行一些初始化操作。同时,还可以通过配置文件中的init方法或者注解的方式指定初始化方法。 6. Bean的后置处理:Spring提供了很多Bean的后置处理器,可以在Bean的初始化前后进行一些额外的处理,例如Bean的属性赋值、Proxy创建等。 7. Bean的销毁:当Spring容器关闭时,会调用Bean的销毁方法进行资源的释放和清理工作。销毁方法可以通过实现DisposableBean接口、配置文件中的destroy方法或者注解的方式指定。 以上是Spring Bean创建过程的主要步骤。Spring利用配置文件和反射机制,将Bean的创建、依赖注入和初始化等过程解耦,提供了灵活和可扩展的开发方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值