Spring5源码解析1-从启动容器开始
从启动容器开始
最简单的启动spring的代码如下:
@Configuration
@ComponentScan
public class AppConfig {
}
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
context.close();
}
}
先来看一下AnnotationConfigApplicationContext
类的UML图,留个印象。
点开AnnotationConfigApplicationContext(AppConfig.class);
方法查看源码:
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
//调用默认无参构造器,里面有一大堆初始化逻辑
this();
//把传入的Class进行注册,Class既可以有@Configuration注解,也可以没有@Configuration注解
//怎么注册? 委托给了 org.springframework.context.annotation.AnnotatedBeanDefinitionReader.register 方法进行注册
// 传入Class 生成 BeanDefinition , 然后通过 注册到 BeanDefinitionRegistry
register(annotatedClasses);
//刷新容器上下文
refresh();
}
该构造器允许我们传入一个或者多个class对象。class对象可以是被@Configuration
标注的,也可以是一个普通的Java 类。
有参构造器调用了无参构造器,点开源码:
public AnnotationConfigApplicationContext() {
//隐式调用父类构造器,初始化beanFactory,具体实现类为DefaultListableBeanFactory
super(); // 这个代码是笔者添加的,方便定位到super方法
//创建 AnnotatedBeanDefinitionReader,
//创建时会向传入的 BeanDefinitionRegistry 中 注册 注解配置相关的 processors 的 BeanDefinition
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
初始化子类时会先初始化父类,会默认调用父类无参构造器。AnnotationConfigApplicationContext
继承了GenericApplicationContext
,在GenericApplicationContext
的无参构造器中,创建了BeanFactory
的具体实现类DefaultListableBeanFactory
。spring中的BeanFactory
就是在这里被实例化的,并且使用DefaultListableBeanFactory
做的BeanFactory
的默认实现。
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
AnnotationConfigApplicationContext
的构造器中还创建了两个对象:AnnotatedBeanDefinitionReader
和 ClassPathBeanDefinitionScanner
。
先说scanner
的作用,通过查看源码可以发现,这个scanner
只有在手动调用AnnotationConfigApplicationContext
的一些方法的时候才会被使用(通过后面的源码探究也可以发现,spring并不是使用这个scanner
来扫描包获取Bean的)。
创建AnnotatedBeanDefinitionReader
对象。spring在创建reader
的时候把this
当做了参数传给了构造器。也就是说,reader
对象里面包含了一个this
对象,也就是AnnotationConfigApplicationContext
对象。AnnotationConfigApplicationContext
实现了BeanDefinitionRegistry
接口。点开this.reader = new AnnotatedBeanDefinitionReader(this);
源码:
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}
从传入的BeanDefinitionRegistry
对象,也就是AnnotationConfigApplicationContext
对象中获取Environment
(共用同一个Environment
),然后又接着调用另一个构造器。点开源码:
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
//在 BeanDefinitionRegistry 中注册 注解配置相关的 processors
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
在这个构造器中,执行了一个非常重要的方法AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
,顾名思义,spring通过这个方法注册了解析注解配置相关的处理器。点开源码:
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
registerAnnotationConfigProcessors(registry, null);
}
//再点开源码
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
//org.springframework.context.annotation.internalConfigurationAnnotationProcessor - ConfigurationClassPostProcessor.class
//这个类非常的重要,它是一个 BeanDefinitionRegistryPostProcessor
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
} catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
- 该方法从传入的
BeanDefinitionRegistry
对象,也就是AnnotationConfigApplicationContext
对象中获取到DefaultListableBeanFactory
对象。 - 为获取的
DefaultListableBeanFactory
对象设置属性 - 往
DefaultListableBeanFactory
对象中注册BeanDefinition
,注册的是一些spring内置的PostProcessor的BeanDefinition
(关于BeanDefinition
的介绍下期在讲)。注意,此时只是注册BeanDefinition
,并没有实例化bean。默认情况下,执行完该方法后,spring容器中所注册的BeanDefinition
为:
源码学习笔记:https://github.com/shenjianeng/spring-code-study
Spring5源码解析1-从启动容器开始的更多相关文章
- Spring5源码解析系列一——IoC容器核心类图
基本概念梳理 IoC(Inversion of Control,控制反转)就是把原来代码里需要实现的对象创建.依赖,反转给容器来帮忙实现.我们需要创建一个容器,同时需要一种描述来让容器知道要创建的对象 ...
- Spring5源码解析-Spring框架中的单例和原型bean
Spring5源码解析-Spring框架中的单例和原型bean 最近一直有问我单例和原型bean的一些原理性问题,这里就开一篇来说说的 通过Spring中的依赖注入极大方便了我们的开发.在xml通过& ...
- Spring5源码解析-论Spring DispatcherServlet的生命周期
Spring Web框架架构的主要部分是DispatcherServlet.也就是本文中重点介绍的对象. 在本文的第一部分中,我们将看到基于Spring的DispatcherServlet的主要概念: ...
- Netty源码解析---服务端启动
Netty源码解析---服务端启动 一个简单的服务端代码: public class SimpleServer { public static void main(String[] args) { N ...
- Spring5源码解析_IOC之容器的基本实现
前言: 在分析源码之前,我们简单回顾一下SPring核心功能的简单使用: 容器的基本用法 Bean是Spring最核心的东西,Spring就像是一个大水桶,而Bean就是水桶中的水,水桶脱离了水就没有 ...
- Spring源码解析二:IOC容器初始化过程详解
IOC容器初始化分为三个步骤,分别是: 1.Resource定位,即BeanDefinition的资源定位. 2.BeanDefinition的载入 3.向IOC容器注册BeanDefinition ...
- Spring5源码解析5-ConfigurationClassPostProcessor (上)
接上回,我们讲到了refresh()方法中的invokeBeanFactoryPostProcessors(beanFactory)方法主要在执行BeanFactoryPostProcessor和其子 ...
- Spring源码解析一:IOC容器设计
一.IOC接口设计 IOC容器设计的源码主要在spring-beans.jar.spring-context.jar这两个包中.IOC容器主要接口设计如下: 这里的接口设计有两条主线:BeanFact ...
- Spring源码解析三:IOC容器的依赖注入
一般情况下,依赖注入的过程是发生在用户第一次向容器索要Bean是触发的,而触发依赖注入的地方就是BeanFactory的getBean方法. 这里以DefaultListableBeanFactory ...
随机推荐
- Java之线程安全
什么是线程安全? 如果有多个线程在同时运行,而这些线程可能会同时运行这段代码.程序每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的. 什么是线程安全问题? ...
- [算法模板]FFT-快速傅里叶变换
[算法模板]FFT-快速傅里叶变换 感谢ZYW聚聚为我们讲解FFT~ 思路 我懒,思路和证明部分直接贴链接: rvalue LSJ-FFT与NTT基础 代码 主要思想是利用了单位根特殊的性质(n次单位 ...
- [译]Vulkan教程(08)逻辑设备和队列
[译]Vulkan教程(08)逻辑设备和队列 Introduction 入门 After selecting a physical device to use we need to set up a ...
- 基于appium的fixture应用之代码重构
一.痛点分析 在appium自动化中,会话启动参数较多,我们使用了yaml配置文件来进行管理,并使用了PyYaml模块进行yaml文件内容的读取,我们知道,在测试场景中,不可能只会用到一种启动类型的参 ...
- Jrebel实现tomcat热部署,遇到的问题以及解决办法,详解
我的安装的详细过程: 下载Jrebel: https://github.com/ilanyu/ReverseProxy/releases/tag/v1.4 我的是winx64,所以选择如下的: 下载 ...
- Spring中,关于IOC和AOP的那些事
一.spring 的优点? 1.降低了组件之间的耦合性 ,实现了软件各层之间的解耦 2.可以使用容易提供的众多服务,如事务管理,消息服务等 3.容器提供单例模式支持 4.容器提供了AOP技术,利用它很 ...
- 压测 swoole_websocket_server 性能
概述 这是关于 Swoole 入门学习的第十篇文章:压测 swoole_websocket_server 性能. 第九篇:Swoole Redis 连接池的实现 第八篇:Swoole MySQL 连接 ...
- PalletOne调色板Token PTN跨链转网的技术原理
之前一直在忙于通用跨链公链PalletOne的研发,没有怎么做技术分享的博客,最近PalletOne主网上线也有几个月的时间了,即将进行PTN(PalletOne上面的主Token)从ERC20到主网 ...
- Typescript使用字符串联合类型代替枚举类型
TypeScript宗旨 我觉得Typescript的宗旨是 任何一个 TypeScript 程序,在手动删去类型部分,将后缀改成 .js 后,都应能够正常运行.Typescript是javascri ...
- 矩阵的运算:Python语言实现
一.矩阵的加减法 import numpy as np #这里是矩阵的加法 ar1=np.arange(10).reshape(10,1) ar1 ar2=np.arange(10).reshape( ...