[英]How to add properties to a spring boot application context on run time
我有一個 Spring 啟動應用程序和一個屬性文件config.properties ,其中的值是加密的(請參見下面的示例)
config.properties
myapp.property1={5AES123}SafeR70/wqqwwqwqwqwqsdaWQmNs+O2afeIU/1MHoCWvTgxUYA30C/rrei4\=
myapp.property2={5AES342}MareV70/PLNqsasasaa*ksueoHH+O2afeIU/1MHoCWvTgxUYJQ30C/7rei4\=
myapp.property3={5AES111}TutoV10/xdtghshI5CVULQ7uevr+O2afeIU/1MHoCWvTgxUYJQ30C/1rei4\=
我正在使用特殊的 API(作為我的應用程序的 POM 依賴項添加)來解密這些值。
請在下面找到一個偽代碼,以更好地解釋我的意圖以及我希望在一天結束時擁有的東西。
public static void main(String[] args) {
// 1. decrypt the properties values of the config.properties using my special API package.
List<MyPropDecrypted> myPropDecryptedLst = mySpecialAPIPack.decrpyt("config.properties");
// 2. get the spring context
myAppSpringContext = getSpringContext();
//3. add the decrypted properties to the spring context from step 2.
int idx = 0;
for (MyPropDecrypted myPropDecrypted : myPropDecryptedLst){
idx++;
myAppSpringContext.setProperty("myapp.property"+idx, myPropDecrypted.getDecrypteValue();
}
SpringApplication.run(Application.class, args);
}
我的問題是如何以編程方式將那些解密的(使用我的特殊 API)屬性添加/注入到 spring 上下文中,以便我可以像從屬性文件加載的屬性一樣使用它(@Value("${myapp.property1}") )?
您可以使用 Spring Cloud Config 並實現自定義 EnvironmentRepository bean,如下所述:
自定義復合環境存儲庫 除了使用 Spring Cloud 中的環境存儲庫之一,您還可以提供自己的 EnvironmentRepository bean,作為復合環境的一部分。 為此,您的 bean 必須實現 EnvironmentRepository 接口。 如果您想在復合環境中控制自定義 EnvironmentRepository 的優先級,您還應該實現 Ordered 接口並覆蓋 getOrdered 方法。 如果您不實現 Ordered 接口,則 EnvironmentRepository 的優先級最低。
我建議您像這樣創建配置 class :
@ConfigurationProperties
@Configuration
class MyConfig{
public Map<String,String > myapp;
public String getproperty1() {
return myapp.get("property1");
}
public String getProperty2() {
//
}
//getters and setter for all the three properties
}
現在更新您的 PSEUDO 代碼以使用 setter 方法設置解密的值。 然后,您可以在任何其他 class 中注入 MyConfig class 並獲取值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.