如何設定 Visual Studio Code 開發 Spring Boot 的時候可以讀取 .env 檔案
source link: https://blog.miniasp.com/post/2021/08/12/Read-envFile-for-Spring-Boot-app-in-Visual-Studio-Code
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
使用 Visual Studio Code 開發 Spring Boot 的時候,我們在 application.yml
檔案中會放入一些環境變數,每次啟動應用程式的時候都要手動設定環境變數才能正常啟動,使用上比較不方便。本篇文章我將說明如何設定 Visual Studio Code 在啟動 Spring Boot 應用程式時,可以自動載入 .env
檔案,讓應用程式啟動時可以自動載入環境變數,增加開發的方便性。
-
請建立一個
.vscode/launch.json
啟動設定檔這裡設定的重點在於
envFile
這一項參數設定,這項設定可以幫助你在啟動時自動載入.env
檔案,並設定好環境變數才會啟動應用程式。{ "configurations": [ { "type": "java", "request": "launch", "name": "Launch Spring Boot", "mainClass": "${workspaceFolder}/src/main/java/com/example/demo1/Demo1Application.java", "envFile": "${workspaceFolder}/.env" } ] }
-
建立
.env
環境變數定義檔你可以使用
SERVER_PORT
指定應用程式要跑在哪個 Port 埠號,這樣就可以不用設定在src/main/resources/application.properties
檔案中!SERVER_PORT=8081 DB_HOST=127.0.0.1:50000 DB_NAME=ADBPDB DB_USERID=userid DB_PASSWD=passwd
以下是
application.yml
的設定範例:spring: jpa: database: db2 datasource: url: jdbc:db2://${DB_HOST}/{DB_NAME}:currentSchema=PFADBP; username: ${DB_USERID} password: ${DB_PASSWD} driver-class-name: com.ibm.db2.jcc.DB2Driver
-
將
.env
加入.gitignore
檔案中一般來說
.env
裡面會包含一些敏感資料,所以預設應該將該檔案加入到.gitignore
中,以免敏感資料被加入版控。 -
按下
F5
啟動應用程式之後無論你在哪裡,都可以按下
F5
啟動 Spring Boot 應用程式,而且會在啟動前設定好環境變數。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK