Spring5源码解析1-从启动容器开始

2024-05-13 10:32

本文主要是介绍Spring5源码解析1-从启动容器开始,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

从启动容器开始
最简单的启动spring的代码如下:
@Configuration@ComponentScanpublic 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) {            thrownew 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为:

 

更多学习资料可关注:annalin1203获取

这篇关于Spring5源码解析1-从启动容器开始的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/985445

相关文章

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析(结合应用场景)

《nginx-t、nginx-sstop和nginx-sreload命令的详细解析(结合应用场景)》本文解析Nginx的-t、-sstop、-sreload命令,分别用于配置语法检... 以下是关于 nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析,结合实际应