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,所以需要做对应的升级处理。

相关推荐
蓝色王者21 小时前
springboot 2.6.13 整合flowable6.8.1
java·spring boot·后端
Tao____1 天前
基于Ruoyi开发的IOT物联网平台
java·网络·物联网·mqtt·网络协议
花哥码天下1 天前
apifox登录后设置token到环境变量
java·后端
浩瀚地学1 天前
【Java】常用API(二)
java·开发语言·经验分享·笔记·学习
hashiqimiya1 天前
springboot事务触发滚动与不滚蛋
java·spring boot·后端
因我你好久不见1 天前
Windows部署springboot jar支持开机自启动
windows·spring boot·jar
PPPHUANG1 天前
一次 CompletableFuture 误用,如何耗尽 IO 线程池并拖垮整个系统
java·后端·代码规范
恩创软件开发1 天前
创业日常2026-1-8
java·经验分享·微信小程序·小程序