--- title: 'Spring Boot 多環境配置' disqus: hackmd --- ###### tags: `SpringBoot` Spring Boot 多環境配置 === [TOC] ## 適用場景 假設你有兩種環境需要部署,一個是 dev(開發環境) 一個是 prod (生產環境),這時多環境配置就可以派上用場。 比如說本機端測試的時候是某個spread sheet,但當正式使用的時候當然要換成另外一個spread sheet了,我們會有不同的spread sheet id在不同的檔案中。 我們可以統一把檔案都放在src/main/resources資料夾裡面,這也會是spring boot的一個預設路徑 @PropertySource註解,告訴了我們,如果要使用@value註解的注入值,**那麼要讀取的那個檔案,究竟在哪裡** ## 先備條件 ## 檔案結構目錄  最重要的關鍵就在ServiceProperties的註解和application.properties有對應   ## 程式碼部分 ### application.properties ``` # To decide which environment to use # prod or dev spring.profiles.active=prod # let the spring boot will shut down when finish spring.main.web-application-type=none #log logging.config=classpath:logback-spring.xml ``` ### service-dev ``` # spread sheet id SpreadSheet.ID=1sP5BeCtcG4l0MnOfTaKxJKFzUTbkpwLqulxxiYaWrKw ``` ### service-prod ``` # spread sheet id SpreadSheet.ID=159tAs3toZ42rfeyMhuxmz7tGUBovFv99zJy910ZNsc8 ``` ### ServiceProperties ```java= package com.example.value.properties; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource(value = "classpath:service-${spring.profiles.active}.properties", encoding="UTF-8") public class ServiceProperties { @Value("${SpreadSheet.ID}") String MainSpreadSheetID; public String getMainSpreadSheetID() { return MainSpreadSheetID; } public void setMainSpreadSheetID(String mainSpreadSheetID) { MainSpreadSheetID = mainSpreadSheetID; } } ``` ## 參考連結
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up