--- title: 在 Tomcat & VSCODE 上更改 spring boot 啟動環境,以讀取環境設定檔 tags: 技術文件 description: 寫文件💩 紀錄一下 --- # 在 Tomcat & VSCODE 上更改 spring boot 啟動環境,以讀取環境設定檔 紀錄一下我怎麼做的 有其他方法請留言告訴我 以下使用環境使用"dev"示範,可以根據自己的需求改環境 ## spring 設置 1. 在src/main/resources下增加設定黨(xx.properties & xx-[環境].properties) ![](https://i.imgur.com/L3y43TR.png) - aaaTestConfig.properties 內容 ```properties= Ver=AAAAA ``` - aaaTestConfig-dev.properties 內容 ```properties= Ver=AAAAA_dev ``` 2. 在src/main/com/xxx/config下增加讀取方式 @PropertySource ,若是使用application.properties 有更方便的方式(待補)。 ![](https://i.imgur.com/gyLvE4n.png) - AAATestConfig.java 內容,ignoreResourceNotFound是必要的 ```java= package com.xxx.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component @PropertySource(value = "classpath:aaaTestConfig.properties", encoding = "UTF-8") @PropertySource(value = "classpath:aaaTestConfig-${spring.profiles.active:default}.properties", ignoreResourceNotFound = true, encoding = "UTF-8") public class AAATestConfig { @Value("${Ver}") private String ver; public String getVer() { return ver; } public void setVer(String ver) { this.ver = ver; } } ``` ## Tomcat 改啟動環境 注意! 此方法會將tomcat上所有程式改為dev環境下執行,可能會使其他程式讀取錯誤設定。 沒有找到為單一project設定環境的方法 1. 在 TOMCAT 中新增 bin/setenv.bat 2. 內容為 `set JAVA_OPTS=%JAVA_OPTS% -Dspring.profiles.active=dev` 就可以讀到此檔案之設定,未設定之部分會使用預設檔案 3. 可以設定多個環境去做fallback ### TODO 問題 使用spring包成war檔出版。 放到測試機,命名環境為demo。 在war檔展開後手動增加了xx-demo.properties檔案。 下次換新war檔時按下startup.bat。tomcat會把新的war檔展開,並把舊設定清掉。 - [ ] 要怎麼把xx-demo設定檔保留下來 ## VSCODE 改啟動環境 在launch.json中增加`"args": "--spring.profiles.active=dev"` ```json= { "version": "0.2.0", "configurations": [ { "cwd": "${workspaceFolder}", "sourcePaths": [ "${workspaceFolder}" ], "type": "java", "name": "launch 後端", "request": "launch", // ... "args": "--spring.profiles.active=dev" }, ] } ``` ## 啟動成功可以看到dev字樣 ![](https://i.imgur.com/KspXlhp.png)