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

38 篇文章 0 订阅
本文讨论了SpringBoot和SpringCloud版本的变化,如何在pom.xml中设置合理的依赖,以及application和bootstrap配置文件的区别和使用方式。重点介绍了ConfigFileApplicationListener在配置加载中的作用,以及SpringCloud2020.0.x版本对bootstrap处理的调整。
摘要由CSDN通过智能技术生成

spring 版本以及相关的组件一直在变化,其中一些类或者功能在低版本中有,高版本中去掉了,有的新功能只在高版本有。

为了防止理解问题,pom.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 中。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值