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

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、思路

(1)經過maven的profile功能,在打包的時候,經過-P指定maven激活某個pofile,這個profile裏面配置了一個參數activatedProperties,不一樣的profile裏面的這個參數的值不一樣 web

(2)SpringBoot的application.properties文件裏面spring.profiles.active填的值取上面maven的activatedProperties參數值。spring

這樣能實現的效果爲:app

  • 示例一:
    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參數值

2、案例

(1)項目結構介紹

項目結構以下圖所示,是個常見的SpringBoot項目結構,不一樣環境的propertis文件的後綴不一樣(見圖中紅框處)maven

(2)pom文件中配置maven的profile

maven的profile的配置見下面代碼spa

注意:maven的profile中activatedProperties參數值須要和SpringBoot的不一樣環境Properties文件的後綴同樣。命令行

好比開發環境的Properties的文件名爲application-dev.properties,那麼maven中dev的profile裏面的activatedProperties參數值就應該是dev3d

<profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>

            <properties>
                <activatedProperties>dev</activatedProperties>
            </properties>
        </profile>

        <profile>
            <id>test</id>
            <activation>
                <os>
                    <family>mac</family>
                </os>
            </activation>
            <properties>
                <activatedProperties>test</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的值,這個取值要用@符號來取。具體見下面代碼code

spring.profiles.active\=@activatedProperties@
(4)如何打包

打包時用 mvn clean package -P profile的idblog

若是不加-P參數,那麼默認就是<activeByDefault>true</activeByDefault>所在的profile開發

(5)效果圖

當咱們打包命令爲mvn clean package -P production 時,解壓後的jar包中application.properties配置文件中spring.profiles.active的值自動變成了production

3、小結

(1)該方式優勢:打包後不須要經過命令行參數來切換不一樣環境的配置文件,把指定環境的這一步放到了maven打包的命令上

(2)該方式實際上是利用了maven的profile功能和SpringBoot的profile相結合使用

相關文章
相關標籤/搜索