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

Spring Boot 自动装配原理剖析

ztj100 2025-05-30 19:01 22 浏览 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”发来的消息。

相关推荐

作为后端开发,你知道MyBatis有哪些隐藏的 “宝藏” 扩展点吗?

在互联网大厂后端开发领域,MyBatis作为一款主流的持久层框架,凭借其灵活的配置与强大的数据处理能力,广泛应用于各类项目之中。然而,随着业务场景日趋复杂、系统规模不断扩张,开发过程中常面临SQL...

基于Spring+SpringMVC+Mybatis分布式敏捷开发系统架构(附源码)

前言zheng项目不仅仅是一个开发架构,而是努力打造一套从前端模板-基础框架-分布式架构-开源项目-持续集成-自动化部署-系统监测-无缝升级的全方位J2EE企业级开发解...

基于Java实现,支持在线发布API接口读取数据库,有哪些工具?

基于java实现,不需要编辑就能发布api接口的,有哪些工具、平台?还能一键发布、快速授权和开放提供给第三方请求调用接口的解决方案。架构方案设计:以下是一些基于Java实现的无需编辑或只需少量编辑...

Mybatis Plus框架学习指南-第三节内容

自动填充字段基本概念MyBatis-Plus提供了一个便捷的自动填充功能,用于在插入或更新数据时自动填充某些字段,如创建时间、更新时间等。原理...

被你误删了的代码,在 IntelliJ IDEA中怎么被恢复

在IntelliJIDEA中一不小心将你本地代码给覆盖了,这个时候,你ctrl+z无效的时候,是不是有点小激动?我今天在用插件mybatisgenerator自动生成mapper的时候,...

修改 mybatis-generator 中数据库类型和 Java 类型的映射关系

使用mybatis-generator发现数据库类型是tinyint(4),生成model时字段类型是Byte,使用的时候有点不便数据库的类型和Model中Java类型的关系...

又被问到了, java 面试题:反射的实现原理及用途?

一、反射的实现原理反射(Reflection)是Java在运行时动态获取类的元数据(如方法、字段、构造器等)并操作类对象的能力。其核心依赖于...

Spring Boot 中JPA和MyBatis技术那个更好?

你在进行SpringBoot项目开发时,是不是也经常在选择JPA和MyBatis这两个持久化技术上犯难?面对众多前辈的经验之谈,却始终拿不准哪种技术才最适合自己的项目?别担心,今天咱们就...

Spring Boot (七)MyBatis代码自动生成和辅助插件

一、简介1.1MyBatisGenerator介绍MyBatisGenerator是MyBatis官方出品的一款,用来自动生成MyBatis的mapper、dao、entity的框架,让...

解决MyBatis Generator自动生成.java.1文件

MyBatis框架操作数据库,一张表对应着一个实体类、一个Mapper接口文件、一个Mapper映射文件。一个工程项目通常最少也要几十张表,那工作量可想而知非常巨大的,MyBatis框架替我们想好了解...

Linux yq 命令使用详解

简介yq是一个轻量级、可移植的命令行...

7 段不到 50 行的 Python 脚本,解决 7 个真实麻烦:代码、场景与可复制

“...

Python学不会来打我(62) json数据操作汇总

很多小伙伴学了很久的python一直还是没有把数据类型之间的转换搞明白,上一篇文章我们详细分享了python的列表、元组、字典、集合之间的相互转换,这一篇文章我们来分享json数据相关的操作,虽然严格...

之前3W买的Python全系列教程完整版(懂中文就能学会)

今天给大家带来了干货,Python入门教程完整版,完整版啊!完整版!言归正传,小编该给大家介绍一下这套教程了,希望每个小伙伴都沉迷学习,无法自拔...

x-cmd pkg | grex - 正则表达式生成利器,解决手动编写的烦恼

简介grex是一个旨在简化创作正则表达式的复杂且繁琐任务的库和命令行程序。这个项目最初是DevonGovett编写的JavaScript工具regexgen的Rust移植。但re...

取消回复欢迎 发表评论: