1.引言
當在多配置文件中,需要切換配置文件時,通常的做法都是修改激活的文件名稱,而spring.profiles.active=@profiles.active@ 是配合 maven profile
進行選擇不同配置文件進行啟動,可以避免修改文件,而在maven打包是指定使用哪個配置文件。
2.實戰演練
2.1環境准備
首先使用IDEA創建一個SpringBoot的項目
2.2配置pom
假設目前有三個環境dev、test和prod,那么需要在pom.xml進行配置:
<build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build> <profiles> <profile> <!-- 本地開發環境 --> <id>dev</id> <properties> <profiles.active>dev</profiles.active> </properties> <activation> <!-- 是否默認激活 --> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <!-- 測試環境 --> <id>test</id> <properties> <profiles.active>test</profiles.active> </properties> <activation> <activeByDefault>false</activeByDefault> </activation> </profile> <profile> <!-- 生產環境 --> <id>prod</id> <properties> <profiles.active>prod</profiles.active> </properties> <activation> <activeByDefault>false</activeByDefault> </activation> </profile> </profiles>
上述默認使用dev配置。配置后需要點擊刷新按鈕來刷新maven,然后會看到如下的幾種選擇:
2.3創建配置文件(properties類型)
首先創建application.properties文件,其內容為:
spring.profiles.active=@profiles.active@
創建application-dev.properties:
server.port=8888
創建application-test.properties:
server.port=9999
創建application-prod.properties:
server.port=8080
啟動項目,查看控制台啟動日志,啟動端口是8888,然后關閉。
在Propfiles中勾選test,取消勾選dev,再啟動項目,此時啟動端口是9999,其他環境同理,打包也是類似的方式。
注意:若切換時還是使用上一次環境或報錯,那么需要刷新一下maven再重啟項目。
若是maven命令打包,其方式如下:
mvn clean package -P prod
使用-P指定使用的配置文件即可。無論是自動打包還是使用maven命令打包,最終的環境名稱會配置給application.properties中,即:
spring.profiles.active=prod //這里假設是prod環境打包的
也就是說,免去了頻繁修改配置文件的操作。
2.4創建配置文件(yml類型)
當然還有另一種yml方式配置,目前在使用時發現有問題,待更新!