Spring Boot允许将配置外部化(externalize),这样你就能够在不同的环境下使用相同的代码。你可以使用properties文件,YAML文件,环境变量和命令行参数来外部化配置。使用@Value注解,可以直接将属性值注入到beans中,然后通过Spring的Environment抽象或通过@ConfigurationProperties绑定到结构化对象来访问。
Application属性文件
SpringApplication将从以下位置加载application.properties文件,并把它们添加到Spring Environment中:(内部覆盖外部)
1. 当前目录下的/config
子目录。
2. 当前目录。
3. classpath下的/config
包。
4. classpath根路径(root)。
参数间的引用、配置随机值
当使用application.properties
定义的属性时,Spring会先通过已经存在的Environment
查找该属性,所以你可以引用事先定义的值:可以使用该技巧为存在的Spring Boot属性创建'短'变量,具体参考Section 69.4, “Use ‘short’ command line arguments”。
com.didispace.blog.name=程序员DD
com.didispace.blog.title=Spring Boot 教程
#参数间的引用
com.didispace.blog.desc=${com.didispace.blog.name}正在努力写${com.didispace.blog.title}
#使用随机数
com.didispace.blog.test1=${random.int[10,20]}
命令行属性
命令行中输入:java -jar xxx.jar --server.port=8888
屏蔽命令行属性。设置 SpringApplication.setAddCommandLineProperties(false)。
多环境配置
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识。比如:
application-dev.properties:开发环境
application-test.properties:测试环境
application-prod.properties:生产环境
设置默认加载哪个文件,可以在application.properties文件中通过spring.profiles.active属性来设置。如:
spring.profiles.active=dev
通过命令行激活其它环境中的配置:
执行java -jar xxx.jar --spring.profiles.active=test,可以观察到服务端口被设置为xxx,也就是测试环境的配置(test)
执行java -jar xxx.jar --spring.profiles.active=prod,可以观察到服务端口被设置为xxx,也就是生产环境的配置(prod)
注意:解决 idea中读取配置文件乱码