spring源码-xml解析概述

我们都知道ApplicationContext就是spring的容器,下面我们来看看spring容器是如何启动的。
首先我们来看一下查看的源码的一些背景:
spring版本:spring5

启动的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"
	   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-4.0.xsd">
	<context:component-scan base-package="org.springframework.demo" />
	<bean id = "demo2" class = "org.springframework.demo.Demo2"></bean>
</beans>

demo1类:

@Component
public class Demo1 {

	@Autowired
	private Demo2 demo2;

	@Value("${test.value:test}")
	private String value;

	public void print(){
		System.out.println(demo2);
		System.out.println(value);
	}
}

demo2类:

public class Demo2 {
}

测试启动代码:

@Test
public void testSingleConfigLocation() {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(FQ_SIMPLE_CONTEXT);
	assertThat(ctx.containsBean("demo1")).isTrue();
	ctx.getBean(Demo1.class).print();
	ctx.close();
}

启动测试,进行初始化:

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

	super(parent);
    //将指定的配置文件记录到一个数组中
	setConfigLocations(configLocations);
	if (refresh) {
	    //开始启动容器
		refresh();
	}
}

上面的代码很简单,只是用一个变量记录了配置文件的地址,并调用refresh方法。

@Override
	public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		//启动容器前的准备工作
		prepareRefresh();
		//
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
		//
		prepareBeanFactory(beanFactory);
		try {
			//
			postProcessBeanFactory(beanFactory);
			//
			invokeBeanFactoryPostProcessors(beanFactory);
			//
			registerBeanPostProcessors(beanFactory);
			//
			initMessageSource();
			//
			initApplicationEventMulticaster();
			//
			onRefresh();
			//
			registerListeners();
			//
			finishBeanFactoryInitialization(beanFactory);
			//
			finishRefresh();
		}catch (BeansException ex) {
            //异常处理…………
		}

		finally {
			//
			resetCommonCaches();
		}
	}
}

从上面的代码我们可以看出spring容器的启动共有12步,下面我们分别从每一步进行详细的学习。

发布了81 篇原创文章 · 获赞 16 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/mazhen1991/article/details/100066915
今日推荐