ClassPathXmlApplicationContext

  1. Ioc追本溯源

Ioc追本溯源

提及spring,必然会提到他的ioc Di ,依赖注入,控制反正,从最原始的new一个对象转变为 当你需要啥spring为你提供这个对象,通过set方法,或者构造器对需要的类进行注入。 现在,spring已经成为java行业内的基准,我们看下面这段程序。通过spring的bean工厂获取testB 用来执行spring的print方法,这也就是spring加载bean最基本的案例。

public class TestA {
	public static void main(String[] args) {
		BeanFactory beanFactory;
		beanFactory = new ClassPathXmlApplicationContext("application.xml");
		TestB testB =(TestB) beanFactory.getBean("testb");
		testB.print();
	}
}
class TestB {
	void print()
	{Optional.of("暴击10000点伤害").ifPresent(System.out::println);}
}
<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   id ="testb" class="org.learn.test1.TestB" />
</beans>

一路向上查看ClassPathXmlApplicationContext的继承关系,可以看到ClassPathXmlApplicationContext继承自AbstractApplicationContext 并且实现了ConfigurableApplicationContext,ConfigurableApplicationContext继承自ApplicationContext接口,ApplicationContext继承自BeanFactory,那么,可以认为ClassPathXmlApplicationContext就是一个BeanFactory。接下来继续查看实例化bean工厂的过程。

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

/**
	 * Create a new ClassPathXmlApplicationContext with the given parent,
	 * loading the definitions from the given XML files.
	 * @param configLocations array of resource locations 资源文件的数组。
	 * @param refresh whether to automatically refresh the context, 释放刷新上下文
	 * loading all bean definitions and creating all singletons.加载全部bean并且创建单例
	 * Alternatively, call refresh manually after further configuring the context.
	 * @param parent the parent context 父上下文
	 * @throws BeansException if context creation failed
	 * @see #refresh()
	 */
public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
            //主要通过refresh()方法来完成初始化的操作
			refresh();
		}
	}

/**
	 * 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) {
			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;
		}
	}
    /**
     *获取或创建一个StandardEnvironment 并获取所有的配置文件
     *
     */
    protected String resolvePath(String path) {
		return getEnvironment().resolveRequiredPlaceholders(path);
	}
会调用AbstractApplicationContext类中的关键方法refresh()


public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			// 遍历配置文件添加到spring环境中并校验配置文件错误
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
            //创建bean工厂 加载bean
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			//给bean工厂添加各种处理器等等
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				//子类中调用beanfactory的后置处理
				postProcessBeanFactory(beanFactory);
				//实例化并执行所有后置处理器
				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				//注册bean的解析器
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				//初始化消息源
				initMessageSource();

				// Initialize event multicaster for this context.
				//初始化bean名为applicationEventMulticaster 的事件广播器 没有就创建一个SimpleApplicationEventMulticaster
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				//加载其他的bean 关键方法 ,需要由子类实现onRefresh 默认什么都不做
				onRefresh();

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

				// Instantiate all remaining (non-lazy-init) singletons.
				//实例化剩下的单例bean
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				//初始化一个DefaultLifecycleProcessor
				//发布事件
				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();
			}
		}
	}

///////////////////////
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		}
		return beanFactory;
	}
    
@Override
	protected final void refreshBeanFactory() throws BeansException {
		//如果有bean工厂则销毁所有bean和bean工厂
        if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
            //创建一个DefaultListableBeanFactory
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			customizeBeanFactory(beanFactory);
            //通过XmlBeanDefinitionReader 加载BeanDefinition
            //DefaultBeanDefinitionDocumentReader 解析xml
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}

至此, 我们了解了下spring 的ApplicationContext 初始化的大致流程。