Maven的porfile與SpringBoot的profile結合使用詳解


    使用maven的profile功能,我們可以實現多環境配置文件的動態切換,可參考我的上一篇博客。但隨着SpringBoot項目越來越火,越來越多人喜歡用SpringBoot的profile功能。但是用SpringBoot的profile功能時,一般我們默認激活的profile肯定是開發環境的profile。當我們打成jar包后,如果在生產環境下運行,就需要在運行這個jar包的命令后面加個命令行參數來指定切換的profile。雖然這樣很方便,但是容易忘記加這個參數。
    我們可以通過maven的profile功能和SpringBoot的profile功能結合使用。 效果為:當maven打包時通過profile指定配置為test環境的配置,那么我們SpringBoot里面默認激活的就是test環境的配置。   這樣我們只需要打包時指定profile后,直接運行jar就可以,不需要在命令行加參數了。這個效果就和我們普通web項目使用maven的profile的效果類似了。

一、思路

    (1)通過maven的profile功能,在打包的時候,通過-P指定maven激活某個pofile,這個profile里面配置了一個參數 activatedProperties ,不同的profile里面的這個參數的值不同
    (2)SpringBoot的application.properties文件里面spring.profiles.active填的值取上面maven的 activatedProperties 參數值。
  這樣能實現的效果為:
示例一:
    maven打包命令為   mvn clean package -P test    
    那么application.properties里面的spring.profiles.active值就是maven中 id為test的profile的activatedProperties參數值
示例二:
    maven打包命令為   mvn clean package -P product
    那么application.properties里面的spring.profiles.active值就是maven中 id為product的profile的activatedProperties參數值

二、案例

(1)項目結構介紹
    項目結構如下圖所示,是個常見的SpringBoot項目結構,不同環境的propertis文件的后綴不同(見圖中紅框處)
(2)pom文件中配置maven的profile
    maven的profile的配置見下面代碼
    注意:maven的profile中activatedProperties參數值需要和SpringBoot的不同環境Properties文件的后綴一樣。
    比如開發環境的Properties的文件名為application-develop.properties,那么maven中develop的profile里面的 activatedProperties參數值就應該是develop
    <profiles>
        <profile>
        	<!-- 開發 -->
            <id>develop</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <activatedProperties>develop</activatedProperties>
            </properties>
        </profile>
        <profile>
        	<!-- 測試 -->
            <id>fuy</id>
            <properties>
                <activatedProperties>fuy</activatedProperties>
            </properties>
        </profile>
        <profile>
        	<!-- 生產 -->
            <id>production</id>
            <properties>
                <activatedProperties>production</activatedProperties>
            </properties>
        </profile>
    </profiles>
(3)application.properties中的配置
    在application.properties文件中配置SpringBoot默認激活的propertis文件。這時候spring.profiles.active取上面maven的profile里面配置的activatedProperties的值,這個取值要用@符號來取。 具體 見下面代碼
spring.profiles.active=@activatedProperties@
(4)如何打包
    打包時用 mvn clean package -P profile的id
          如果不加-P參數,那么默認就是 <activeByDefault>true</activeByDefault> 所在的profile
(5)效果圖
          當我們打包命令為mvn clean package -P production 時,解壓后的jar包中application.properties配置文件中spring.profiles.active的值自動變成了production
         

三、小結

(1)該方式優點:打包后不需要通過命令行參數來切換不同環境的配置文件,把指定環境的這一步放到了maven打包的命令上
(2)該方式其實是利用了maven的profile功能和SpringBoot的profile相結合使用

四、參考鏈接


    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM