Spring Boot程序默认从application.properties或者application.yaml读取配置,如何将配置信息外置,方便配置呢?
1. 通过命令行指定
SpringApplication会默认将命令行选项参数转换为配置信息
例如,启动时命令参数指定:
java -jar myproject.jar --server.port = 9000
从命令行指定配置项的优先级最高,不过你可以通过setAddCommandLineProperties来禁用
SpringApplication.setAddCommandLineProperties(false).
2. 外置配置文件
Spring程序会按优先级从下面这些路径来加载application.properties配置文件
当前目录下的/config目录
当前目录
classpath里的/config目录
classpath 跟目录
因此,要外置配置文件就很简单了,在jar所在目录新建config文件夹,然后放入配置文件,或者直接放在配置文件在jar目录
3. 自定义配置文件
如果你不想使用application.properties作为配置文件,怎么办?完全没问题
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
或者
java -jar -Dspring.config.location=D:\config\config.properties springbootrestdemo-0.0.1-SNAPSHOT.jar
当然,还能在代码里指定
@SpringBootApplication
@PropertySource(value={"file:config.properties"})
public class SpringbootrestdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootrestdemoApplication.class, args);
}
}
4. 使用spring cloud config 配置中心
配置中心支持配置的动态下发,十分灵活
5.外部化配置方式与优先级
Spring Boot 允许外化配置,Spring Boot使用了一个特别的PropertySource次序来允许对值进行覆盖,覆盖的优先级顺序如下:
-
Devtools全局设置主目录(~ /.spring-boot-devtools.properties 为活跃的)。
-
@TestPropertySource注解在Test。
-
@SpringBootTest#properties 注解在Test。
-
命令行参数。
-
从SPRING_APPLICATION_JSON属性(内联JSON嵌入在一个环境变量或系统属性)。
-
ServletConfig init参数。
-
ServletContext init参数。
-
JNDI属性java:comp/env。
-
Java系统属性(System.getProperties())。
-
操作系统环境变量。
-
RandomValuePropertySource配置的random.属性值
-
打包在jar以外的application-{profile}.properties或application.yml配置文件
-
打包在jar以内的application-{profile}.properties或application.yml配置文件
-
打包在jar以外的application.properties或application.yml配置文件
-
打包在jar以内的application.properties或application.yml配置文件
-
@configuration注解类上的@PropertySource。
-
默认的属性(使用SpringApplication.setDefaultProperties指定)。