為了便於隱藏用戶名和密碼,我們有時會用到“環境變量”。
Spring Boot提供了很好的機制,可以在配置文件中,如application.yml書寫以下格式,然后在代碼中@Value就可以獲取“環境變量”的值。但這有一個不大不小的坑...
mail:
smtp:
auth: true
host: smtp.xxmail.com
user-name: XX監控中心
user: ${EMAIL_USERNAME}
password: ${EMAIL_PASSWD}
recipients: xx@xxx.com
如果IDEA先打開,環境變量后加入,在IDEA調試代碼時,就會出現無法獲取環境變量的問題,報null的錯,如:
org.springframework.beans.factory.UnsatisfiedDependencyException:..................Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'XXXX' in value "${XXXX}"
解決辦法,很簡單:先加入環境變量,重新打開IDEA即可。
要注意,關閉所有的IDEA再重啟,否則,還是無法加載環境變量。
