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步,下面我们分别从每一步进行详细的学习。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值