Spring Boot 自动装配原理剖析
mhr18 2025-05-11 17:15 6 浏览 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”发来的消息。
相关推荐
- 使用 Docker 部署 Java 项目(通俗易懂)
-
前言:搜索镜像的网站(推荐):DockerDocs1、下载与配置Docker1.1docker下载(这里使用的是Ubuntu,Centos命令可能有不同)以下命令,默认不是root用户操作,...
- Spring Boot 3.3.5 + CRaC:从冷启动到秒级响应的架构实践与踩坑实录
-
去年,我们团队负责的电商订单系统因扩容需求需在10分钟内启动200个Pod实例。当运维组按下扩容按钮时,传统SpringBoot应用的冷启动耗时(平均8.7秒)直接导致流量洪峰期出现30%的请求超时...
- 《github精选系列》——SpringBoot 全家桶
-
1简单总结1SpringBoot全家桶简介2项目简介3子项目列表4环境5运行6后续计划7问题反馈gitee地址:https://gitee.com/yidao620/springbo...
- Nacos简介—1.Nacos使用简介
-
大纲1.Nacos的在服务注册中心+配置中心中的应用2.Nacos2.x最新版本下载与目录结构3.Nacos2.x的数据库存储与日志存储4.Nacos2.x服务端的startup.sh启动脚...
- spring-ai ollama小试牛刀
-
序本文主要展示下spring-aiollama的使用示例pom.xml<dependency><groupId>org.springframework.ai<...
- SpringCloud系列——10Spring Cloud Gateway网关
-
学习目标Gateway是什么?它有什么作用?Gateway中的断言使用Gateway中的过滤器使用Gateway中的路由使用第1章网关1.1网关的概念简单来说,网关就是一个网络连接到另外一个网络的...
- Spring Boot 自动装配原理剖析
-
前言在这瞬息万变的技术领域,比了解技术的使用方法更重要的是了解其原理及应用背景。以往我们使用SpringMVC来构建一个项目需要很多基础操作:添加很多jar,配置web.xml,配置Spr...
- 疯了!Spring 再官宣惊天大漏洞
-
Spring官宣高危漏洞大家好,我是栈长。前几天爆出来的Spring漏洞,刚修复完又来?今天愚人节来了,这是和大家开玩笑吗?不是的,我也是猝不及防!这个玩笑也开的太大了!!你之前看到的这个漏洞已...
- 「架构师必备」基于SpringCloud的SaaS型微服务脚手架
-
简介基于SpringCloud(Hoxton.SR1)+SpringBoot(2.2.4.RELEASE)的SaaS型微服务脚手架,具备用户管理、资源权限管理、网关统一鉴权、Xss防跨站攻击、...
- SpringCloud分布式框架&分布式事务&分布式锁
-
总结本文承接上一篇SpringCloud分布式框架实践之后,进一步实践分布式事务与分布式锁,其中分布式事务主要是基于Seata的AT模式进行强一致性,基于RocketMQ事务消息进行最终一致性,分布式...
- SpringBoot全家桶:23篇博客加23个可运行项目让你对它了如指掌
-
SpringBoot现在已经成为Java开发领域的一颗璀璨明珠,它本身是包容万象的,可以跟各种技术集成。本项目对目前Web开发中常用的各个技术,通过和SpringBoot的集成,并且对各种技术通...
- 开发好物推荐12之分布式锁redisson-sb
-
前言springboot开发现在基本都是分布式环境,分布式环境下分布式锁的使用必不可少,主流分布式锁主要包括数据库锁,redis锁,还有zookepper实现的分布式锁,其中最实用的还是Redis分...
- 拥抱Kubernetes,再见了Spring Cloud
-
相信很多开发者在熟悉微服务工作后,才发现:以为用SpringCloud已经成功打造了微服务架构帝国,殊不知引入了k8s后,却和CloudNative的生态发展脱轨。从2013年的...
- Zabbix/J监控框架和Spring框架的整合方法
-
Zabbix/J是一个Java版本的系统监控框架,它可以完美地兼容于Zabbix监控系统,使得开发、运维等技术人员能够对整个业务系统的基础设施、应用软件/中间件和业务逻辑进行全方位的分层监控。Spri...
- SpringBoot+JWT+Shiro+Mybatis实现Restful快速开发后端脚手架
-
作者:lywJee来源:cnblogs.com/lywJ/p/11252064.html一、背景前后端分离已经成为互联网项目开发标准,它会为以后的大型分布式架构打下基础。SpringBoot使编码配置...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- oracle位图索引 (63)
- oracle批量插入数据 (62)
- oracle事务隔离级别 (53)
- oracle 空为0 (50)
- oracle主从同步 (55)
- oracle 乐观锁 (51)
- redis 命令 (78)
- php redis (88)
- redis 存储 (66)
- redis 锁 (69)
- 启动 redis (66)
- redis 时间 (56)
- redis 删除 (67)
- redis内存 (57)
- redis并发 (52)
- redis 主从 (69)
- redis 订阅 (51)
- redis 登录 (54)
- redis 面试 (58)
- 阿里 redis (59)
- redis 搭建 (53)
- redis的缓存 (55)
- lua redis (58)
- redis 连接池 (61)
- redis 限流 (51)