這是我的第一個問題,所以如果它不夠具體,我深表歉意(請溫柔哈哈)并且我已經閱讀了檔案,但我是該領域的新手,沒有任何幫助。
我正在制作一個使用 Java 18 和 Spring Boot 來呼叫外部 API 呼叫的簡單專案,并且出于明顯的原因,我想隱藏我使用的 API 密鑰。
截至目前,我的資源目錄中有一個 application-dev.properties 檔案,其中包含以下內容(我正在撰寫實際的安全密鑰)并且我的 .gitignore 檔案中有 application-dev.properties 所以它沒有承諾:
api-key=someText
我正在嘗試在我的控制器中使用該值,如下所示:
@RestController
public class ImageController {
@Value("${api-key}")
private String API_KEY;
@RequestMapping(value = "/image")
public List<String> getImages(@RequestParam(defaultValue = "4") String request) {
String url = "https://api.nasa.gov/planetary/apod?" API_KEY request;
RestTemplate restTemplate = new RestTemplate();
我收到的錯誤是這樣的:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'imageController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'api-key' in value "${api-key}"
提前致謝!
uj5u.com熱心網友回復:
正如您所提到的,您正在使用application-dev.properties因此您必須正確進行分析。在您application.properties添加spring.profiles.active=dev以激活開發組態檔。
uj5u.com熱心網友回復:
如另一個答案中所述, application-dev.properties 檔案的名稱要求您激活“dev”組態檔,否則 Spring Boot 將永遠不會讀取它,并且其中的值將不可用于您的@Value注釋。
這是一篇討論 Spring Boot 組態檔的 Baeldung 文章的鏈接:Baeldung 的 Spring Boot Profiles (我與 Baeldung 無關,我只是喜歡他們的很多東西)。
如果您不打算在應用程式中使用組態檔,請將屬性檔案的名稱更改為“application.properties”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/510017.html
標籤:爪哇春天弹簧靴行家
