百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术教程 > 正文

Spring Boot 自动装配原理剖析

mhr18 2025-05-11 17:15 24 浏览 0 评论

前言

在这瞬息万变的技术领域,比了解技术的使用方法更重要的是了解其原理及应用背景。以往我们使用 Spring MVC 来构建一个项目需要很多基础操作:添加很多 jar,配置 web.xml,配置 Spring 的 XML 或 javaConfig 类。而 SpingBoot 给我们省略了很多基础工作,快速开发,不用再写繁琐的 XML,而这些都由各种 Starter 组件及自动装配来替代。

什么是 Starter,什么是自动装配呢?对于 Spring Boot,我们不仅要会用,也要明白其原理,很可能你面试就被问到。本文将通过分析源码讲解 Spring Boot 的自动装配原理,通过自己动手写一个 Starter 组件来帮助大家加深理解。

什么是自动装配

什么是自动装配,Spring Boot 是怎么实现自动装配的呢?先来看个例子。

首先我们新建一个 Maven 工程,引入
spring-boot-starter-data-redis:

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

在配置文件中添加数据源:

spring.redis.host=localhost
#密码
spring.redis.password=
#单节点 默认 6379
spring.redis.port=6379

写一个测试类:

/**
 * @author Mr.Fire
 * @date 2021/8/14 11:03
 * @desc
 */
@Service
public class DistributedCache {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    public boolean exists(Object key) {
        return false;
    }

    public List<ValueWrapper> mGet(List<? extends String> keys) {
         List<Object> valueList = redisTemplate.opsForValue().multiGet(createCacheKeys(keys));
         return valueList.stream().map(t -> new SimpleValueWrapper(t)).collect(Collectors.toList());
    }
    ...
}

我们并没有通过过 XML 的形式或注解的方式把 RedisTemplate 装配到 IOC 容器中。却可以直接使用 @Autowired 注入 RedisTemplate 来使用。说明 IOC 容器中已经存在 bean,这就是 Spring Boot 的自动装配,相信大家都不陌生,接下来讲解其原理。

自动装配原理分析

Spring Boot 的自动装配是通过 EnableAutoConfiguration 注解来开启的。下面我们来看看这个注解。

下面这段代码是笔者的一个 Demo 程序入口。

/**
 * @author Mr.Fire
 */
@EnableCaching
@SpringBootApplication
@MapperScan("com.fire.blog.mapper")
public class ServerApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        new SpringApplicationBuilder(ServerApplication.class).beanNameGenerator(new BeanNameGenerator()).run(args);
    }

}

EnableAutoConfiguration 声明在 @SpringBootApplication 中。点击进入源码,可以看到 @EnableAutoConfigurationde 声明。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * @return the classes to exclude
     */
    @AliasFor(annotation = EnableAutoConfiguration.class)
    Class<?>[] exclude() default {};

    /**
     * Exclude specific auto-configuration class names such that they will never be
     * applied.
     * @return the class names to exclude
     * @since 1.3.0
     */
    @AliasFor(annotation = EnableAutoConfiguration.class)
    String[] excludeName() default {};
    ...

进入到 @EnableAutoConfiguration:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

    /**
     * Environment property that can be used to override when auto-configuration is
     * enabled.
     */
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * @return the classes to exclude
     */
    Class<?>[] exclude() default {};

这里我们主要关注两个:

  • @AutoConfigurationPackage:该注解的作用是将 添加该注解的类所在的 package 作为 自动配置 package 进行管理。通俗来讲就是把使用了该注解的类所在的包及其子包下的所有组件扫描到 IOC 容器中。
  • @Import(AutoConfigurationImportSelector.class):Import 注解是用来导入配置类或者一些需要前置加载的类。该注解有三种用法:带有 @Configuration 的配置类ImportSelector 的实现ImportBeanDefinitionRegistrar 的实现

这里我们看到的 @Import 正是用的第二种方式,导入的一个
AutoConfigurationImportSelector 类。该类实现了 ImportSelector 接口。ImportSelector 和 Configuration 的区别就是可以批量选择装配哪些 bean,接下来我们重点分析这个类。

定位到
AutoConfigurationImportSelector 类:

public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
        ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {

源码太长,此处省略了具体的实现,看文章时尽量自己到源码中看。

可以看到
AutoConfigurationImportSelector 实现了 ImportSelector 的 selectImports 方法,这个方法可以选择性返回需要装配的 bean,返回结果是一个数组。改方法主要实现两个功能:

  • 从 META-INF/spring.factories 加载配置类
  • 筛选出符合条件的配置类集合

下面是 selectImports 的具体实现:

@Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        if (!isEnabled(annotationMetadata)) {
            return NO_IMPORTS;
        }
        AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationMetadata); 
        return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());  
    }

selectImports 方法里通过调用 getAutoConfigurationEntry 拿到 AutoConfigurationEntry 配置对象,在通过
autoConfigurationEntry.getConfigurations() 拿到所有符合条件的配置类。

getAutoConfigurationEntry 方法分析:

protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
        if (!isEnabled(annotationMetadata)) {
            return EMPTY_ENTRY;
        }
        AnnotationAttributes attributes = getAttributes(annotationMetadata);
        List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
        configurations = removeDuplicates(configurations);
        Set<String> exclusions = getExclusions(annotationMetadata, attributes);
        checkExcludedClasses(configurations, exclusions);
        configurations.removeAll(exclusions);
        configurations = getConfigurationClassFilter().filter(configurations);
        fireAutoConfigurationImportEvents(configurations, exclusions);
        return new AutoConfigurationEntry(configurations, exclusions);
    }
  • getAttributes:获得 @EnableAutoConfiguration 注解中的 exclude、excludeName 属性
  • getCandidateConfigurations:获得所有自动装配的配置类
  • removeDuplicates:去除重复配置项
  • checkExcludedClasses:根据 exclude、excludeName 属性移除不需要的配置
  • fireAutoConfigurationImportEvents:广播事件
  • AutoConfigurationEntry:返回过滤后的配置类

如何获得这些配置类呢,这里关键看
getCandidateConfigurations 方法。

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
                getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
                + "are using a custom packaging, make sure that file is correct.");
        return configurations;
    }

这里用到了 SpringFactoriesLoader,Spring 内部提供的一种加载方式,类似于 Java 的 SPI 机制,主要是扫描 classpath 下的 META-INF/spring.factories 文件,spring.factories 是 key=value 的形式存储,SpringFactoriesLoader 根据 key 得到 value,来看 loadFactoryNames 方法:

public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
        ClassLoader classLoaderToUse = classLoader;
        if (classLoaderToUse == null) {
            classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
        }
        String factoryTypeName = factoryType.getName();
        return loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
    }

这里的 loadSpringFactories 方法内部实现就是扫描所有 META-INF/spring.factories 文件,构建成一个 Map<String, List>,key 为 factoryTypeName,value 为基于 javaConfig 形式的配置类集合。接下来就是把这些 Bean 都装配到 IOC 容器中,到这我们就明白 Spring Boot 是如何实现自动装配。

自动装配分析完了,来总结下核心步骤:

  • 通过@Import(AutoConfigurationImportSelector.class)导入实现类
  • 实现 ImportSelector 的 selectImports 方法,选择性批量装配配置类
  • 通过 Spring 提供的 SpringFactoriesLoader 机制,扫描 META-INF/spring.factories
  • 读取需要装配的配置类,筛选符合条件的配置类,把不符合的排除
  • 通过 javaConfig 的形式装配 Bean

Starter 命名规范

什么是 Starter,文章开头引入的
spring-boot-starter-data-redis 就是一个标准的官方 Starter 组件。Starter 内部定义了相关 jar 包的依赖,而我们不需要一个一个去引入相关 jar,实现了 bean 自动装配,自动声明并且加载 properties 文件属性配置。

命名规范:

  • 官方:spring-boot-starter-模块名称
  • 自定义:模块名称-spring-boot-starter

手写一个 starter 组件

基于前面所讲自动装配原理,我们从 0 到 1 写一个自定义的 Starter 组件来加深大家对自动装配的理解。下面是基于消息中间件 RabbitMQ 写一个自定义 Starter 组件,不了解 RabbitMQ 的朋友可以参阅我之前的文章,到具体的客户端使用该组件详细步骤。

1. 创建一个名为 mq-spring-boot-starter 的 maven 项目 目录结构:

添加 jar 包依赖,pom 文件中引入 spring-rabbit(spring 对 RabbitMQ 的一个封装):

 <dependency>
     <groupId>org.springframework.amqp</groupId>
     <artifactId>spring-rabbit</artifactId>
     <version>2.3.10</version>
     <scope>compile</scope>
 </dependency>

2. 定义属性类

该属性类配置 RabbitMQ 的 IP、端口、用户名、密码等信息。由于只是一个简单的 Demo,只定义了一些简单的参数。前缀为 fire.mq,对应 properties/yml 中的属性。

/**
 * @author Mr.Fire 
 * @date 2021/8/15 17:35
 * @desc
 */
@ConfigurationProperties(prefix = "fire.mq")
public class RabbitMqProperties {

    private String address = "localhost";

    private int port = 5672;

    private String userName;

    private String password;

    ...
}

3. 定义配置类

  • 通过 @Configuration 声明为一个配置类
  • @EnableConfigurationProperties(RabbitMqProperties.class):导入属性类
  • @Bean 注解方式上声明一个 connectionFactory 的 bean 对象,设置用户名密码等
  • 通过 FireRabbitTemplate 的构造方法传入 connectionFactory
  • @ConditionalOnClass:表示一个条件,当前 classpath 下有这个 class,才会实例化一个 Bean

注:这里的 FireRabbitTemplate 为我自定义的一个类,继承自了 RabbitTemplate,下面步骤有写。

/**
 * @author Mr.Fire 
 * @date 2021/8/15 17:40
 * @desc
 */
@Configuration
@EnableConfigurationProperties(RabbitMqProperties.class)
public class RabbitMqConfig {

    @Bean
    @ConditionalOnClass(ConnectionFactory.class)
    FireRabbitTemplate fireRabbitTemplate(ConnectionFactory connectionFactory) {
        FireRabbitTemplate rabbitTemplate = new FireRabbitTemplate(connectionFactory,"fireMQ");
        //数据转换为 json 存入消息队列
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        return rabbitTemplate;
    }

    @Bean
    ConnectionFactory connectionFactory(RabbitMqProperties rabbitMqProperties){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
        connectionFactory.setHost(rabbitMqProperties.getAddress());
        connectionFactory.setPort(rabbitMqProperties.getPort());
        connectionFactory.setUsername(rabbitMqProperties.getUserName());
        connectionFactory.setPassword(rabbitMqProperties.getPassword());
        return connectionFactory;
    }
}

4. 自定义的 RabbitTemplate

定义一个有 name 的 RabbitTemplate,继承自 RabbitTemplate,通过名字测试可以直观看到效果。

注:RabbitTemplate 是 Spring 对 RabbitMQ 的一个封装好的模板接口,类似于 RedisTemplate。

/**
 * @author Mr.Fire
 * @date 2021/8/15 17:42
 * @desc
 */
public class FireRabbitTemplate extends RabbitTemplate {

    private String name="fireMQ";


    public FireRabbitTemplate(ConnectionFactory connectionFactory,String name) {
        super(connectionFactory);
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

5. 关键一步,在 resources 目录下新建 spring.factories 文件,key-value 形式配置写好的 Config 类。使 Spring Boot 可以扫描到文件完成自动装配。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.fire.mq.rabbitmq.RabbitMqConfig

至此,一个非常简单的自定义 Starer 组件已经完成。我们只需要安装到本地仓库,其他项目就可以引用该组件了。

6. 执行命令 mvn install 到本地仓库。

注:安装前需要把 spring-boot-maven-plugin 给去掉。

测试

接下来我们新建一个测试工程来引入我们写好的 Starter 组件,测试一下效果。

1. 新建一个简单的测试工程 starter-cilent,目录结构如下:

2. 引入自定义的 Starter:

<dependency>
   <groupId>com.fire</groupId>
   <artifactId>mq-spring-boot-starter</artifactId>
   <version>0.0.1-SNAPSHOT</version>
</dependency>

3. 编写测试代码

这里写一个 Web 接口用来模拟发消息,发到对应的 helloQueue 队列中,监听这个队列的消费者就能消费这条消息。

定义 rest 接口:注入自定义 Starter 组件中的 FireRabbitTemplate 模板接口类,调用发消息的方法。

/**
 * @author Mr.Fire
 * @date 2021/8/15 17:48
 * @desc
 */
@RestController
public class MqRestController {

    @Autowired
    FireRabbitTemplate rabbitTemplate;

    @GetMapping("/send")
    public String sendMsg(){
        String msg = "这是一条来自"+rabbitTemplate.getName()+"的消息!";
        rabbitTemplate.convertAndSend("helloQueue",msg);
        return "success";
    }
}

定义队列:

@Configuration
public class HelloQueue {

    @Bean
    public org.springframework.amqp.core.Queue queue() {
        return new org.springframework.amqp.core.Queue("helloQueue");
    }
}

定义消费者,监听 helloQueue 队列,并打印收到的消息。

@Configuration
public class Consumer {

    @RabbitListener(queues = "helloQueue")
    @RabbitHandler
    public void receive(String msg) {
        System.out.println("Consumer 收到消息:" + msg);
    }

}

4. 配置文件 appliction.properties

这里默认本地已经安装 RabbitMQ,需要的朋友可以看我的前一篇文章。

fire.mq.address=localhost
fire.mq.port=5672
fire.mq.username=guest
fire.mq.password=guest
server.port=8081

5. 启动测试

浏览器输入
http://localhost:8081/send,看控制台输出:

这说明自己写的 Starter 组件已经生效,成功收到“fireMq”发来的消息。

相关推荐

【推荐】一个开源免费、AI 驱动的智能数据管理系统,支持多数据库

如果您对源码&技术感兴趣,请点赞+收藏+转发+关注,大家的支持是我分享最大的动力!!!.前言在当今数据驱动的时代,高效、智能地管理数据已成为企业和个人不可或缺的能力。为了满足这一需求,我们推出了这款开...

Pure Storage推出统一数据管理云平台及新闪存阵列

PureStorage公司今日推出企业数据云(EnterpriseDataCloud),称其为组织在混合环境中存储、管理和使用数据方式的全面架构升级。该公司表示,EDC使组织能够在本地、云端和混...

对Java学习的10条建议(对java课程的建议)

不少Java的初学者一开始都是信心满满准备迎接挑战,但是经过一段时间的学习之后,多少都会碰到各种挫败,以下北风网就总结一些对于初学者非常有用的建议,希望能够给他们解决现实中的问题。Java编程的准备:...

SQLShift 重大更新:Oracle→PostgreSQL 存储过程转换功能上线!

官网:https://sqlshift.cn/6月,SQLShift迎来重大版本更新!作为国内首个支持Oracle->OceanBase存储过程智能转换的工具,SQLShift在过去一...

JDK21有没有什么稳定、简单又强势的特性?

佳未阿里云开发者2025年03月05日08:30浙江阿里妹导读这篇文章主要介绍了Java虚拟线程的发展及其在AJDK中的实现和优化。阅前声明:本文介绍的内容基于AJDK21.0.5[1]以及以上...

「松勤软件测试」网站总出现404 bug?总结8个原因,不信解决不了

在进行网站测试的时候,有没有碰到过网站崩溃,打不开,出现404错误等各种现象,如果你碰到了,那么恭喜你,你的网站出问题了,是什么原因导致网站出问题呢,根据松勤软件测试的总结如下:01数据库中的表空间不...

Java面试题及答案最全总结(2025版)

大家好,我是Java面试陪考员最近很多小伙伴在忙着找工作,给大家整理了一份非常全面的Java面试题及答案。涉及的内容非常全面,包含:Spring、MySQL、JVM、Redis、Linux、Sprin...

数据库日常运维工作内容(数据库日常运维 工作内容)

#数据库日常运维工作包括哪些内容?#数据库日常运维工作是一个涵盖多个层面的综合性任务,以下是详细的分类和内容说明:一、数据库运维核心工作监控与告警性能监控:实时监控CPU、内存、I/O、连接数、锁等待...

分布式之系统底层原理(上)(底层分布式技术)

作者:allanpan,腾讯IEG高级后台工程师导言分布式事务是分布式系统必不可少的组成部分,基本上只要实现一个分布式系统就逃不开对分布式事务的支持。本文从分布式事务这个概念切入,尝试对分布式事务...

oracle 死锁了怎么办?kill 进程 直接上干货

1、查看死锁是否存在selectusername,lockwait,status,machine,programfromv$sessionwheresidin(selectsession...

SpringBoot 各种分页查询方式详解(全网最全)

一、分页查询基础概念与原理1.1什么是分页查询分页查询是指将大量数据分割成多个小块(页)进行展示的技术,它是现代Web应用中必不可少的功能。想象一下你去图书馆找书,如果所有书都堆在一张桌子上,你很难...

《战场兄弟》全事件攻略 一般事件合同事件红装及隐藏职业攻略

《战场兄弟》全事件攻略,一般事件合同事件红装及隐藏职业攻略。《战场兄弟》事件奖励,事件条件。《战场兄弟》是OverhypeStudios制作发行的一款由xcom和桌游为灵感来源,以中世纪、低魔奇幻为...

LoadRunner(loadrunner录制不到脚本)

一、核心组件与工作流程LoadRunner性能测试工具-并发测试-正版软件下载-使用教程-价格-官方代理商的架构围绕三大核心组件构建,形成完整测试闭环:VirtualUserGenerator(...

Redis数据类型介绍(redis 数据类型)

介绍Redis支持五种数据类型:String(字符串),Hash(哈希),List(列表),Set(集合)及Zset(sortedset:有序集合)。1、字符串类型概述1.1、数据类型Redis支持...

RMAN备份监控及优化总结(rman备份原理)

今天主要介绍一下如何对RMAN备份监控及优化,这里就不讲rman备份的一些原理了,仅供参考。一、监控RMAN备份1、确定备份源与备份设备的最大速度从磁盘读的速度和磁带写的带度、备份的速度不可能超出这两...

取消回复欢迎 发表评论: