我在 pod 中安裝了一個包含用戶名和密碼的卷。如果我做 ,
kubectl exec -it my-app -- cat /mnt/secrets-store/git-token
{"USERNAME":"usernameofgit","PASSWORD":"dhdhfhehfhel"}
我想使用 spring boot 讀取這個 USERNAME 和 PASSWORD。由于我是新手,有人可以幫我解決這個問題。
uj5u.com熱心網友回復:
掛載卷后,您需要做的就是從 Spring Boot 應用程式讀取 JSON 檔案。我建議閱讀從 JSON 檔案加載 Spring Boot 屬性。
簡而言之,您可以創建一個與您的 JSON 檔案相對應的類,就像這樣。
@Component
@PropertySource("file:/mnt/secrets-store/git-token")
@ConfigurationProperties
public class GitToken {
private String username;
private String password;
// getters and setters
}
然后,您需要將其添加到componentScan并自動裝配您的類。
uj5u.com熱心網友回復:
假設:
- 檔案 (git_token) 格式是固定的 (JSON)。
- 該檔案可能沒有擴展名后綴 (.json)。
...我們有一些問題!
我試過2.3.5。匯入無擴展檔案,例如:
spring.config.import=/mnt/secrets-store/git-token[.json]
但它只適用于 YAML/.properties!(用 spring-boot:2.6.1 測驗))
同樣適用于2.8。型別安全的配置屬性。;(;(
在 Spring-Boot 中,我們可以(開箱即用)提供 JSON-config(僅)作為SPRING_APPLICATION_JSON環境/命令列屬性,它必須是 json string,并且不能是路徑或檔案(還)。
提議的 (baeldung) 文章展示了“啟用 JSON 屬性”的方法,但它是一篇包含許多細節的長篇文章,展示了大量代碼并且有相當多的缺失/過時(@ConfigurationProperties 上的 @Component 相當“非常規”)。
我嘗試了以下操作(在本地機器上,在上述假設下):
package com.example.demo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Value("#{@jacksonObjectMapper.readValue(T(java.nio.file.Files).newInputStream(T(java.nio.file.Path).of('/mnt/secrets-store/git-token')), T(com.example.demo.GitInfo))}")
GitInfo gitInfo;
@Bean
CommandLineRunner runner() {
return (String... args) -> {
System.out.println(gitInfo.getUsername());
System.out.println(gitInfo.getPassword());
};
}
}
@Data
class GitInfo {
@JsonProperty("USERNAME")
private String username;
@JsonProperty("PASSWORD")
private String password;
}
使用(僅)spring-boot-starter-web 和 lombok,它會列印預期的輸出。
解決方案概述:
- 一個 pojo 為此
- 大寫的問題不大,但可以如圖所示進行處理。
- 一個 (crazy)
@Value- (Spring-) 運算式,涉及:- (希望)自動配置的
@jacksonObjectMapperbean。(或者:自定義) - ObjectMapper#readValue(可能的替代方案)
- java.nio.file.Files#newInputStream(可能的替代方案)
- java.nio.file.Path#of
- (希望)自動配置的
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/386204.html
標籤:春天 弹簧靴 Kubernetes spring-boot-maven-plugin spring-boot-admin
