Spring/Spring Boot的外部化配置
不論是一個簡單的Java程序或者是基於Spring或者Spring Boot框架實現的程序,都存在外部化配置信息的需求,例如一個抽獎程序需要制定隨機器的種子值,或者與數據庫建立連接的url/username/password,這些配置信息你都不希望直接固定寫入程序中,因此需要一種方式能夠外部化制定這些配置信息,在代碼的對這些數據的使用點讀取對應的配置來實現動態化程序的行為。
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
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)
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
Spring/Spring Boot的外部化配置