文章目录
- 一、Spring继承结构
- 二、Spring容器的启动方式
- 三、快速理解Spring容器的加载流程
-
- 1. 容器的构造函数
- 2. 容器加载的核心方法 refresh()
-
- 2.1 核心方法 refresh() 介绍
- 2.2 核心流程 - prepareRefresh()
- 2.3 核心流程 - obtainFreshBeanFactory()
- 2.4 核心流程 - prepareBeanFactory(beanFactory);
- 2.5 核心流程 - postProcessBeanFactory(beanFactory);
- 2.6 核心流程 - invokeBeanFactoryPostProcessors(beanFactory);
- 2.7 核心流程 - registerBeanPostProcessors(beanFactory);
- 2.8 核心流程 - initMessageSource();
- 2.9 核心流程 - initApplicationEventMulticaster();
- 2.10 核心流程 - onRefresh();
- 2.11 核心流程 - registerListeners();
- 2.12 核心流程 - finishBeanFactoryInitialization(beanFactory);
- 2.13 核心流程 - finishRefresh();
- 四、总结
一、Spring继承结构
1. Spring容器的继承结构
常见的容器的实现类有ClassPathXmlApplicationContext、AnnotationConfigApplicationContext这两个实现类。其中一种是基于XML解析的实现类,一种是基于注解扫描的实现类。
2. Spring工厂的继承结构
Spring中默认的工厂的实现类就是DefaultListableBeanFactory,还有一些别名和单例相关的接口没有在图中绘制。
###3、什么是BeanDefinition?
在高版本的Spring中,BeanDefinition是上图中的内容,可以看到BeanDefinition中有很多属性,其中每个属性有不同的含义,有一些是标识类信息和bean名称的,有继承关系的属性,是否懒加载的属性,是否可被依赖的属性,创建销毁方法指定的属性等。这些属性在Bean的实例化创建过程中起到至关重要的作用。
二、Spring容器的启动方式
1. 通过加载XML的方式
启动Spring容器的方式,在以往WEB项目中,我们是基于web.xml中配置标签来启动一个Spring容器的。
<!--初始化spring 容器:-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring5/exercise/web01/spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
该启动方式是通过类路径来加载spring.xml配置文件来启动Spring容器。在启动的过程中,Spring会对配置文件中配置的一些标签来加载并保存Bean的定义,最后统一通过这些Bean的定义来实例化并缓存对象。
1.1 手动创建加载XML的Spring容器
@Test
public void run01(){
// 基于加载XML配置文件的方式,启动spring容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:spring5/**/demo01/spring.xml");
ProductService productService = (ProductService) context.getBean("productService");
productService.show();
}
2. 通过扫描注解的方式
当下SpringBoot大行其道,抛开XML配置,基于扫描扫描包/类注解的方式来启动Spring容器才是当下的主流。
2.1 手动创建扫描包路径的Spring容器
@Test
public void run02(){
// 基于扫描注解的方式,启动spring容器
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext("com.jd.nlp.dev.muzi.spring5.exercise.demo01");
ProductService productService = (ProductService) context.getBean("productService");
productService.show();
}
2.2 手动创建扫描类注解的Spring容器
@Test
public void run06(){
// 基于扫描注解的方式,启动spring容器 ScanClass配置了@ComponentScan注解
AnnotationConfigApplicationContext context =
new AnnotationConfigAppli