springboot 區分不一樣環境配置

通常來講,項目開發分爲開發環境(dev)測試環境(test)預生產環境(pre)生產環境(prod)。不一樣環境之間的配置存在必定的差別,咱們須要根據不一樣的部署環境切換配置文件,下面來講一下如何區分不一樣環境進行配置。java

配置文件準備

準備下圖對應的application-*.properties文件。spring

  • application.properties: 公共配置
  • application-dev.properties: 開發環境配置
  • application-test.properties: 測試環境配置
  • application-prod.properties: 生產環境配置

image.png

pom.xml配置

<resources>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.yml</include>
            <include>**/*.xml</include>
        </includes>
        <!-- 是否替換@xx@表示的maven properties屬性值 -->
        <filtering>true</filtering>
    </resource>
</resources>

application.properties

# 此時配置爲開發環境
spring.profiles.active=dev

# 此時配置爲測試環境
spring.profiles.active=test

# 此時配置爲生產環境
spring.profiles.active=prod

上面的配置須要咱們在不一樣環境的時候修改對應的值,這樣來講很是的不方便,此時咱們能夠經過變量的方式進行配置,下面咱們進行修改。springboot

pom.xml中添加app

<profiles>
    <!--開發環境-->
 <profile>
        <id>dev</id>
        <properties>
            <env>dev</env>
        </properties>
    </profile>
    <!--測試環境-->
 <profile>
        <id>test</id>
        <properties>
            <env>test</env>
        </properties>
    </profile>
    <!--生產環境-->
 <profile>
        <id>prod</id>
        <properties>
            <env>prod</env>
        </properties>
    </profile>
</profiles>

application.properties修改成maven

# 此時經過env來區分不一樣環境
spring.profiles.active=@env@

這時咱們在IDEA右側看到以下:spring-boot

在這裏咱們能夠選擇對應的環境測試

image.png

此時咱們已經能夠經過切換Profiles來切換環境了。可是這種狀況下只能經過運行啓動類的方式進行啓動,像這樣:spa

image.png

這樣的話才能夠應用到Profiles選中的值。code

spring-boot:run方式啓動xml

此時不能應用到IDEA右側選中的Profiles的環境值。


  • mvn spring-boot:run -P dev

咱們須要在命令後添加指定的環境,像這樣:mvn spring-boot:run -P dev指定以dev的環境進行啓動,其中-P指定pom.xml中對應的profiles的值。此時application.properties配置文件再也不生效。


springboot1.x啓動

  • mvn spring-boot:run -Drun.profiles=dev

springboot2.x啓動

  • mvn spring-boot:run -Dspring-boot.run.profiles=test

運行jar包

java -jar -Dspring.profiles.active=test demo.jar

# 或者

java -jar --spring.profiles.active=test demo.jar
相關文章
相關標籤/搜索