spring boot(2.4.x之前版本)和spring cloud项目中配置文件的作用

为了防止理解问题,pom.xml 版本依赖如下

XML 复制代码
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.3.12.RELEASE</version>
	<relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-dependencies</artifactId>
			<version>Hoxton.SR12</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-alibaba-dependencies</artifactId>
			<version>2.2.6.RELEASE</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>

日常开发中经常使用的配置文件有 application 和 bootstrap(日志相关的例外不做讲解),对应的配置文件后缀分别为 properties 或者 yml(yaml),区别如下

application

属于 spring boot。

简单使用不依赖其他服务,spring boot 的依赖足够。

bootstrap

属于 spring cloud,位于 spring-cloud-context 中。

XML 复制代码
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-context</artifactId>
  <version>3.0.0</version>
</dependency>

可以看到,在 spring.factories 中声明了 ApplicationListener 的实现类 BootstrapApplicationListener,所以,开源组件如果想要使用 spring cloud 的组件一般都会引入这个。

想要读取对应的配置需要结合 BootstrapApplicationListener 进行读取。

如果未引入 spring-cloud-context 相关依赖,bootstrap 相关配置文件则无法找到。

idea 对应的文件图标颜色发生改变

引入了依赖

未引入依赖

其中,对应的配置加载都通过 ConfigFileApplicationListener 来处理。

github 上源码如下

https://github.com/spring-projects/spring-boot/blob/v2.3.12.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/package-info.java

https://github.com/spring-projects/spring-boot/blob/v2.3.12.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java

可以发现,ConfigFileApplicationListener 位于 spring boot 中。

从 spring cloud 2020.0.x 版本开始,针对 bootstrap 的处理发生改变,由于 spring cloud 2020.0.x 对应的 spring boot 版本为 2.4.x,所以需要做对应的升级处理。

相关推荐
mldong7 小时前
"applicant" 契约:退回发起人的闭环设计
java·架构
月华路7 小时前
G1 垃圾回收:脏卡队列、记忆集与并发精化线程机制
java·开发语言
gugucoding8 小时前
47. 【Java】Java内存模型(JMM)与可见性
java·开发语言
zww89491118 小时前
校园跑腿系统开发实战指南:从需求分析到上线部署全流程解析
java
Fluxart.ai9 小时前
电商商品图审核怎么自动化?规则引擎、人工复核与发布门禁
java·前端·自动化
名字还没想好☜9 小时前
Java 线上内存泄漏排查实战:jmap 导堆、MAT 找 GC Roots 与四类常见泄漏
java·开发语言·jvm·内存泄漏
IT爱学堂11 小时前
尚硅谷 - 2025年3月Java+AI大模型应用开发
java·开发语言·人工智能
小贤plus12 小时前
SpringBoot 三大核心注解精讲:@ControllerAdvice、@RestControllerAdvice、@Validated 分组校验(实战)
java
吠品12 小时前
Java byte数组与String互转:编码细节与踩坑记录
java·linux·服务器
晚风醉蝶12 小时前
1-6-插入排序-InsertionSort
java·数据结构·排序算法