首页
学习
活动
专区
圈层
工具
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在 Spring Boot 项目中,同时存在这两种配置文件,先加载谁?

在一个 Spring Boot 项目中,同时存在 application.properties 和 bootstrap.properties 这两种配置文件,在项目启动时,先加载哪个配置,后加载哪个配置,你知道吗?

平时很少关注,今天就来了解下。

在 Spring Boot 和 Spring Cloud 项目中,application.properties和bootstrap.properties的加载顺序的确有所不同,尤其是在涉及到Spring Cloud时。

一、bootstrap.properties的加载顺序

Spring Boot 会首先加载application.properties或application.yml文件,而bootstrap.properties(或者bootstrap.yml)通常用于Spring Cloud项目,尤其是与配置中心(如 Spring Cloud Config)配合使用时。

bootstrap.properties是在 Spring Boot 启动时加载的第一个配置文件,它会在application.properties之前加载。

这是因为 Spring Cloud 会在启动过程中首先需要加载bootstrap.properties中的配置,以便连接到 Spring Cloud 配置中心(如 Spring Cloud Config)进行远程配置的加载。它通常包含像配置中心地址应用名称等与配置相关的设置。

bootstrap.properties会在Spring ApplicationContext 启动之前进行加载。

application.properties 则是在 Spring ApplicationContext 已经创建后,才会被加载。

二、 Spring Boot 和 Spring Cloud 版本的区别

从 Spring Boot 1.x 到 2.x,application.properties和application.yml的加载顺序没有变化,始终是application.properties被加载在最后。

Spring Cloud 依赖于bootstrap.properties,并且会优先加载这个文件,特别是在使用 Spring Cloud Config 时。Spring Cloud 的不同版本在某些配置项上可能有所不同,但整体的加载顺序通常不会变。

不过在 Spring Cloud 2020.0.x 及以后的版本中,有些配置可能会有所变化,特别是 Spring Cloud Config 的处理方式,不再主动加载 bootstrap.propertie 配置文件,如果需要加载,还需要添加 spring-cloud-starter-bootstrap 框架进行支持。

  <groupId>org.springframework.cloud</groupId>   <artifactId>spring-cloud-starter-bootstrap</artifactId>   <version>4.2.0</version>

三、加载顺序总结

Spring Cloud 项目,首先加载bootstrap.properties:用于加载与配置中心相关的配置,或者一些需要在应用启动前加载的配置。然后加载application.properties:用于应用的常规配置。

Spring Boot 项目,只有application.properties或application.yml,不会涉及到bootstrap.properties,所以只有application.properties会被加载。

bootstrap.properties(Spring Cloud 配置中心相关配置):

spring.application.name=my-app

spring.cloud.config.uri=http://config-server:8888

spring.cloud.config.label=master

application.properties(应用本地配置)

server.port=8080

spring.datasource.url=jdbc:mysql://localhost:3306/mydb四、最后总结

Spring Boot 项目只有application.properties,因此仅加载该文件。

有 Spring Cloud 的 Spring Boot 项目会先加载bootstrap.properties,然后加载application.properties。

如何验证先加载的哪个配置文件,在项目启动时增加参数:

--logging.level.org.springframework.boot.context.config=DEBUG

通过它我们就可以看到先加载的哪个配置文件。

  • 发表于:
  • 原文链接https://page.om.qq.com/page/Oul_OH38fr1y-Xpod-aCxGvw0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券