在Spring Boot中,配置文件的优先级和加载顺序如下:
bootstrap.yml(或bootstrap.properties):用于应用程序启动阶段,比应用程序自身的配置先加载。一般用于由Spring Cloud配置的边缘场景,比如配置元数据,服务发现等。application.yml(或application.properties):是最常用的配置文件,用于应用程序的正常运行。- 环境变量:Spring Boot 会自动把环境变量中以
SPRING_APPLICATION_JSON打头的部分或以SPRING_APPLICATION_打头的部分转换为Spring的配置。 - 命令行参数:启动应用时传递的参数,如
--spring.profiles.active=prod。 @SpringBootTest注解的测试中,@TestPropertySource注解指定的属性。@SpringBootApplication注解的properties属性或@SpringBootTest注解的properties属性。- 由
RandomValuePropertySource生成的random.*属性。 - 由
SpringApplication的addListeners添加的任何ApplicationListener。 @PropertySource注解的属性文件。- 默认属性,通过
SpringApplication.setDefaultProperties设置的属性。
优先级从高到低,即bootstrap.yml的优先级最高,其次是命令行参数,然后是环境变量,最后是application.yml。
这里是一个简单的例子,展示如何使用这些配置文件:
bootstrap.yml:
spring:
cloud:
config:
uri: http://config-serverapplication.yml:
spring:
profiles:
active: @activatedProperties@
---
spring.profiles: dev
message: This is the development message
---
spring.profiles: prod
message: This is the production message启动时可以通过命令行参数来指定激活哪个配置,如:
java -jar yourapp.jar --spring.profiles.active=prod这样,应用就会加载与“prod” profile 相关联的配置。