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

相关推荐
xurileidian26 分钟前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python
Mikko72 小时前
Redis 主从切换期间可用吗?6.2 实测哨兵切换:应用不可写 33 秒,主从连不上、数据不一致,以及设了 ACL 后哨兵不切换
java·运维·redis·后端
不得了zz2 小时前
11-Agent 可观测与评估:Spring AI Alibaba Admin Studio 到底解决了什么
java·人工智能·后端·spring·ai编程·springaialibaba
软件技术NINI2 小时前
基于 SpringBoot 的酒店预定系统
java·spring boot·后端
软件技术NINI2 小时前
基于 Spring Boot 中国历史知识学习系统
spring boot·后端·学习
田里的水稻3 小时前
FA_排序算法-冒泡排序
java·算法·排序算法
她的男孩4 小时前
会签选了候选角色,发起却报 nrOfInstances:Forge Admin 改成按人展开集合
spring boot·低代码·工作流引擎
会编程的吕洞宾4 小时前
Spring Cloud Gateway 限流鉴权与灰度发布实战
java·经验分享·后端·spring
学长毕设5 小时前
基于SpringBoot 宠物商城领养网站-附源码
spring boot·后端·宠物
AI开源软件6 小时前
SpringCloud+Nacos 业务协同落地:业务调用与集成中心远程管理如何分别配置
java·spring boot