Springboot的默认配置文件加载路径及优先级
Springboot的默认配置文件加载路径有5种,优先级高于外部扩展配置(Externalized Configuration)。
也就是说:springboot配置文件的优先级为:
T0:springboot默认的5种配置文件加载路径。
T1:18种外部扩展配置。
其中,18种外部扩展配置顺序参见上面那个官方链接。
默认的5种配置文件加载路径如下:
首先一个文件名称通用原则:
在相同文件夹下如果有application.properties和application.yml两个文件,那么application.properties文件会覆盖application.yml文件,生效的是application.properties文件。
其次路径优先级原则:
* {@link EnvironmentPostProcessor} that configures the context environment by loading
* properties from well known file locations. By default properties will be loaded from
* 'application.properties' and/or 'application.yml' files in the following locations:
* <ul>
* <li>file:./config/</li>
* <li>file:./config/{@literal *}/</li>
* <li>file:./</li>
* <li>classpath:config/</li>
* <li>classpath:</li>
* </ul>
// Note the order is from least to most specific (last one wins)
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/";以执行java -jar命令的目录为“根目录”。注意不一定是jar所在的目录。
说明如下:
file:./config/ 进程根目录下的config目录
file:./config/*/ 上面的子目录
file:./ 进程根目录
classpath:config/ classpath下的config/
classpath: classpath下
注意,再次强调,不能用 外部扩展配置 来代替 springboot的默认配置。例如
--spring.config.location=optional:classpath:/default.properties,optional:classpath:/override.properties --spring.config.additional-location=file:/xxx/
这些配置都无法代替springboot的默认配置优先级,有些高优先级的配置加载,例如nacos的启动配置
bootstrap.yml内如如下:
### ------------nacos config center
spring.cloud.nacos.config:
enabled: true
server-addr: ${spring.cloud.nacos.discovery.server-addr}
username: ${spring.cloud.nacos.discovery.username}
password: ${spring.cloud.nacos.discovery.password}
namespace: ${DEPLOY_ENV}
group: ${spring.application.name}
name: application
file-extension: yml就必须放在默认配置路径下,放在外部扩展配置下是无效的。