内部配置
通过前面的学习我们已经知道 SpringBoot 的配置文件有两种,application.properties
和 application.yml
,这两种配置文件是放在工程内的,所以在此我们将它归类为内部配置。而这些配置文件不仅仅只能放在 classpath
根目录下,且当它们放在不同的目录下时加载顺序是有顺序的,具体如下:
./config/application.properties
./config/application.yml
./application.properties
./application.yml
classpath:config/application.properties
classpath:config/application.yml
classpath:application.properties
classpath:application.yml
注(经测试部分 SpringBoot 版本下标 1-4 失效):
- 如果同一个目录下有
application.yml
也有application.properties
,默认先读取application.properties
。- 如果同一个配置属性,在多个配置文件都配置了,默认使用第 1 个读取到的,后面读取的不覆盖前面读取到的。
- 创建 SpringBoot 项目时,一般的配置文件放置在 classpath 根目录。
外部配置
SpringBoot 的配置文件不仅仅只能存在于工程内部,还可以存在于以下位置(摘自官方文档),优先级从高到低,高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置。
1、Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
2、@TestPropertySource annotations on your tests.
3、properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
4、Command line arguments.
5、Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
6、ServletConfig init parameters.
7、ServletContext init parameters.
8、JNDI attributes from java:comp/env.
9、Java System properties (System.getProperties()).
10、OS environment variables.
11、A RandomValuePropertySource that has properties only in random.*.
12、Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants).
13、Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants).
14、Application properties outside of your packaged jar (application.properties and YAML variants).
15、Application properties packaged inside your jar (application.properties and YAML variants).
16、@PropertySource annotations on your @Configuration classes.
17、Default properties (specified by setting SpringApplication.setDefaultProperties).
下面是整理出来的可能会用到的方式:
1、命令行参数。
2、来自 java:comp/env 的 JNDI 属性。
3、java 系统属性(System.getProperties())。
4、操作系统环境变量。
5、RandomValuePropertySource 配置的 random.* 属性值。
# 优先加载带 profile 的配置
6、jar 包外部的 application-{profile}.properties 或 application.yml(带 spring.profile)的配置文件。
7、jar 包内部的 application-{profile}.properties 或 application.yml(带 spring.profile)的配置文件。
# 再来加载不带 profile 的配置
8、jar 包外部的 application.properties 或 application.yml(不带 spring.profile)的配置文件。
9、jar 包内部的 application.properties 或 application.yml(不带 spring.profile)的配置文件。
10、@Configuration 注解类上的 @PropertySource。
11、通过 SpringApplication.setDefaultProperties 指定的默认属性。
还可以通过 spring.config.location
属性来指定配置文件位置,不过这种方式需要是在项目打包以后通过命令行启动项目时来指定配置文件新位置,指定配置文件和默认加载的配置文件会一起起作用形成互补配置,例如: java -jar demo1-0.0.1-SNAPSHOT.jar --spring.config.location=F://application.properties
。通过命令行方式运行 jar 文件不指定配置文件路径时默认也会加载和 jar 文件同级目录的配置文件。
评论区