在 Spring Boot 的 application.properties 中使用環境變量
一、概述
在本文中,我們將解釋如何在 Spring Boot 的application.properties
中使用環境變量。然後我們將展示如何在代碼中引用這些屬性。
2.在application.properties
文件中使用環境變量
讓我們定義一個名為 JAVA_HOME 的全局環境變量,其值為“C:\Program Files\Java\jdk-11.0.14”。
要在 Spring Boot 的 application.properties 中使用這個變量,我們需要用大括號括起來:
java.home=${JAVA_HOME}
我們也可以以同樣的方式使用系統屬性。例如,在 Windows 上,默認定義一個 OS 屬性:
environment.name=${OS}
也可以組合幾個變量值。讓我們定義另一個環境變量 HELLO_BAELDUNG,其值為“Hello Baeldung”。我們現在可以像這樣連接我們的兩個變量:
baeldung.presentation=${HELLO_BAELDUNG}. Java is installed in the folder: ${JAVA_HOME}
property
baeldung.presentation
現在包含以下文本:“Hello Baeldung。 Java 安裝在文件夾中:C:\Program Files\Java\jdk-11.0.14”。
這樣,我們的屬性根據環境具有不同的值。
3. 在代碼中使用我們的環境特定屬性
鑑於我們啟動了一個 Spring 上下文,現在讓我們解釋一下如何將屬性值注入到我們的代碼中。
3.1。使用@Value
注入值
首先,我們可以使用@Value
註解。 @Value
處理 setter、構造函數和字段注入:
@Value("${baeldung.presentation}")
private String baeldungPresentation;
3.2.從 Spring 環境中獲取
我們還可以通過 Spring 的Environment
獲取屬性的值。我們需要自動裝配它:
@Autowired
private Environment environment;
由於getProperty
方法,現在可以檢索屬性值:
environment.getProperty("baeldung.presentation")
3.3.使用 @ConfigurationProperties 對屬性進行分組
如果我們想將屬性組合在一起, @ConfigurationProperties
註釋非常有用。我們將定義一個Component
來收集具有給定前綴的所有屬性,在我們的例子中baeldung
。然後我們可以為每個屬性定義一個 setter。設置器的名稱是屬性名稱的其餘部分。在我們的例子中,我們只有一個叫做presentation
:
@Component
@ConfigurationProperties(prefix = "baeldung")
public class BaeldungProperties {
private String presentation;
public String getPresentation() {
return presentation;
}
public void setPresentation(String presentation) {
this.presentation = presentation;
}
}
我們現在可以自動裝配BaeldungProperties
對象:
@Autowired
private BaeldungProperties baeldungProperties;
最後,要獲取特定屬性的值,我們需要使用相應的 getter:
baeldungProperties.getPresentation()
4。結論
在本教程中,我們了解瞭如何根據環境定義具有不同值的屬性並在代碼中使用它們。
與往常一樣,代碼可在 GitHub 上獲得。