15.配置文件加载优先级和外部配置文件加载

 

配置文件加载优先级和外部配置文件加载

1. 内部的配置文件加载

1.1 内部配置文件的加载有哪些目录

  1. classpath:./: 编译路径下的根目录(src/main/resources)
  2. classpath:/config: 编译路径下的config目录(src/main/resources/config)
  3. ./: 项目的根目录
  4. ./config: 项目根目录下的config目录

1.2 内部配置文件的加载顺序

同级目录下,properties文件的优先级大于yml文件。

优先加载顺序:

  1. ./config: 项目根目录下的config目录
  2. ./: 项目的根目录
  3. classpath:/config: 编译路径下的config目录(src/main/resources/config)
  4. classpath:./: 编译路径下的根目录(src/main/resources)

配置文件加载优先顺序的测试方法:

application.yml

1
2
server:
port: 8092

output:

1
2021-03-31 12:32:41.840  INFO 11488 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8086 (http) with context path ''

1.3 为什么是这四个目录

查看ConfigFileApplicationListener

Eclipse中Ctrl+Shift+T

1
2
3
4
5
6
7
8
@Deprecated
public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {

// 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/";
// ...
}

2. 外部的配置文件加载

2.1 文件加载

优先级:

  1. ./config/application.yml
  2. ./application.yml
1
2
3
4
|-- springboot_config.jar
|-- application.yml
|-- config
|-- application.yml

application.yml

1
2
server:
port: 8092
1
2021-03-31 12:57:23.485  INFO 2100 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8095 (http) with context path ''

3. 属性加载

1
G:\eclipse\eclipse-2020-12\project\demo\jar>java -jar springboot_config.jar --server.port=8100
1
2021-03-31 12:58:30.608  INFO 7936 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8100 (http) with context path ''

4. 总结

优先级:

  1. java -jar springboot_config.jar --server.port=8100
  2. 外部配置文件
  3. 内部配置文件