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

相关文章

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2

Spring Cloud LoadBalancer 负载均衡详解

《SpringCloudLoadBalancer负载均衡详解》本文介绍了如何在SpringCloud中使用SpringCloudLoadBalancer实现客户端负载均衡,并详细讲解了轮询策略和... 目录1. 在 idea 上运行多个服务2. 问题引入3. 负载均衡4. Spring Cloud Load

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解

《如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解》:本文主要介绍如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别的相关资料,描述了如何使用海康威视设备网络SD... 目录前言开发流程问题和解决方案dll库加载不到的问题老旧版本sdk不兼容的问题关键实现流程总结前言作为

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2