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

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

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-11 05:50:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-11 05:50:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-11 05:50:01       82 阅读
  4. Python语言-面向对象

    2024-02-11 05:50:01       91 阅读

热门阅读

  1. 最小生成树——Prim/Kruskal Python

    2024-02-11 05:50:01       51 阅读
  2. 迟旧迎新感悟

    2024-02-11 05:50:01       43 阅读
  3. MySQL中drop、delete与trancate的区别

    2024-02-11 05:50:01       46 阅读
  4. mysql RR、RC隔离级别实现原理

    2024-02-11 05:50:01       43 阅读
  5. 【PyTorch】张量(Tensor)的生成

    2024-02-11 05:50:01       48 阅读
  6. 最关键的十个图像特征

    2024-02-11 05:50:01       41 阅读
  7. 面向字节流编程-TCP协议

    2024-02-11 05:50:01       51 阅读
  8. Nginx访问控制模块详解

    2024-02-11 05:50:01       46 阅读
  9. cf923Div3F题

    2024-02-11 05:50:01       49 阅读