![](/img/trans.png)
[英]How to use Eclipse Variables in Spring Boot application.properties
[英]How to use environment variables with application.properties in spring boot?
我正在嘗試配置我的 application.properties 以從我設置的系統變量中獲取值。 問題是無論我做什么都行不通。 我嘗試使用自定義 class 配置和此示例中的 DataSource 仍然沒有成功。 我在 stackoverflow 上能找到的只是指向官方文檔的鏈接。 不幸的是,這是一條死胡同,因為它什么也沒說,也沒有我想要達到的目標的例子。 我還發現了像spring.datasource.url = ${SPRING_DATASOURCE_URL}
這樣的例子,每個人都在說 Z2A2D595E6ED9A0B24F027F2B63B134D6 會很驚訝它不會自動接受環境變量。
I also found examples like spring.datasource.password = ${SPRING_DATASOURCE_PASSWORD:the_actual_password)
or spring.datasource.url = #{SPRING_DATASOURCE_URL:#{'the_actual_url'}}
wich is totally not what I need and it's pretty useless if you ask me . 我的意思是我可以通過編寫spring.datasource.password = the_actual_password
來實現相同的目標。 漏洞點是隱藏敏感數據..
現在,話雖這么說,我將留下 2 張截圖與我所擁有的。 我之所以嘗試實現這一目標是因為當我推送到 github 時,我不必擔心我的憑據或任何東西都會公開供所有人查看。
這是 application.properties 的樣子。
先感謝您。 如果您對我的問題有答案,您能否讓我知道如何使用環境變量實現相同的功能,但對於應用程序?jwt 屬性?
您是否使用了正確的注釋?
給定這樣的屬性:
root.test = ${TEST.VAR:-Test}
環境變量如:
TEST.VAR = Something
配置 class:
@Configuration
@ConfigurationProperties(prefix = "root")
public class Test {
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
您可以通過在主 class 上設置@ConfigurationPropertiesScan
來使用Records
@SpringBootApplication
@ConfigurationPropertiesScan
public class DemoApplication{...}
像這樣定義記錄:
@ConfigurationProperties(prefix = "root")
public record Test (String test) {
}
好的,解決方案很...愚蠢,我想,但就是這樣。 它不起作用的原因是因為環境變量是在 IntelliJ 首次打開后定義的,如此處所述。 似乎現在一切正常。
我設法實現了我想要的功能。
換句話說:
spring.datasource.url = ${SPRING_DATASOURCE_URL}
spring.datasource.username = ${SPRING_DATASOURCE_USERNAME}
spring.datasource.password = ${SPRING_DATASOURCE_PASSWORD}
spring.datasource.driver-class-name = ${SPRING_DATASOURCE_DRIVERCLASSNAME}
現在工作正常。
謝謝你的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.