通常,我们有2种方式来利用Spring, 第一种方式是使用配置的方式,第二种方式是:注解的方式。
- 配置方式-1
BeanFactory bf = new XmlBeanFactory(new ClasswPthResource("test.xml"));
- 配置方式-2
ApplicationContext ac = new ClassPathXmlApplicationContext("text.xml");
- 包扫描注解的方式
ApplicationContext applicationContext = new AnnotationConfigApplicationContext("com.spring");
本篇文章主要讲解配置方式-2的实现方式。
在讲解之前,有必要说明一下配置方式的两种区别,实际上就是 BeanFactory
和 ApplicationContext
的区别。 两者都是用来加载 bean 的,但ApplicationContext
提供了更多的功能。即ApplicationContext
包含了BeanFactory
的所有功能。实际上从继承关系也可以看出来。
我们从解析xml
作为切入点,来对Spring
的整体进行分析。
一、ClassPathXmlApplicationContext
类
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
我们可以将配置文件路径以数组的方式传递进去,因为他也提供下面这个方法。
public ClassPathXmlApplicationContext(String... configLocations) throws BeansException {
this(configLocations, true, null);
}
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
// 设置配置路径
setConfigLocations(configLocations);
if (refresh) {
// 解析和加载
refresh();
}
}