Spring/Spring Boot的外部化配置
不论是一个简单的Java程序或者是基于Spring或者Spring Boot框架实现的程序,都存在外部化配置信息的需求,例如一个抽奖程序需要制定随机器的种子值,或者与数据库建立连接的url/username/password,这些配置信息你都不希望直接固定写入程序中,因此需要一种方式能够外部化制定这些配置信息,在代码的对这些数据的使用点读取对应的配置来实现动态化程序的行为。
可以实现外部化配置的方式包括:
1. 环境变量(Environment variables), Java程序可以通过API System.getEnv(String key)来获取环境变量列表当中的key/value集合中对应的值。 对于使用Jekin Pipeline或者shell脚本方式运行java程序的方式,环境变量注入配置值是一种可以考虑的方式。
2. Java系统属性(System Properties),
1. 环境变量(System.getEnv)
Environment variables are set in the OS, e.g. in Linux export HOME=/Users/myusername
or on Windows SET WINDIR=C:\Windows
etc, and, unlike properties, may not be set at runtime.
To get a specific environment variable you can use System.getenv(String name)
.
2. Java系统属性(System.getProperties)
System properties are set on the Java command line using the -Dpropertyname=value
syntax. They can also be added at runtime using System.setProperty(String key, String value)
or via the various System.getProperties().load()
methods.
To get a specific system property you can use System.getProperty(String key)
or System.getProperty(String key, String def)
. As it happens, Java chose to expose OS variables as properties (just as Java exposes current directory and "other stuff" as properties)
Different from Environment Variables: https://www.baeldung.com/java-system-get-property-vs-system-getenv
3. spring的外部化配置策略
spring.config.location, 只对spring boot有效,查找配置文件的详细地址。
Property and Enviroment
application.properties/.yml
Common sub project configuration
above spring 3.1 and below spring 3.1 , propertysourceplaceholder propertyplaceholder <context: place-holder> @PropertySource