我們知道,一個項目在開發環境、測試環境、生產環境,不同的環境會有不同的配置,比如數據庫的配置就不同,那麼怎麼樣才能做到,不用每次換環境的時候,都去修改這些配置呢,下面以我寫的一個小案例來作說明。
如下圖是我項目的三個配置文件,其中,application.yml是啓動服務時,服務器會自動加載的配置文件,而application-dev.yml代表的是開發環境的配置文件,application-prod.yml代表的是生產環境的配置文件,後兩個文件在啓動服務時,服務器不會自動加載,那麼在不同的環境中時怎麼調用不同的文件的呢?
方式一、修改配置文件方式
修改application.yml配置文件,具體內容如下圖:
這樣,在啓動服務時,服務器就會通過application.yml文件去調用application-dev.yml文件。同理,若active: prod,那麼服務在啓動時,服務器就會調用application-prod.yml文件。也就是說,在開發環境時,只需將application.yml配置文件配置爲"dev",而生產環境時,只需將“dev”改爲“prod”就可以了。
方式二、命令啓動服務,命令中帶參數方式(此方式可以沒有application.yml文件)
第一步:進入到項目目錄下,先用maven對項目進行打包,會在target目錄下生成項目的jar包
第二步:進入target目錄,執行命令:java -jar 生成的jar包 --spring.profiles.active=prod
項目就會調用application-prod.yml配置文件,即以生產環境的配置要求啓動服務。同理,若是開發環境,只需將prod改爲dev即可。
方式三:爲方式一的更靈活版
application.properties中填寫spring.profiles.active=@activatedProperties@,這裏的@activatedProperties@是一個變量對應pom文件裏的環境配置。
下面是pom文件的配置:
<profiles>
<profile>
<id>dev</id>
<properties>
<!-- 環境標識,需要與配置文件的名稱相對應 -->
<activatedProperties>dev</activatedProperties>
</properties>
<activation>
<!-- 默認環境 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<activatedProperties>test</activatedProperties>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<activatedProperties>prod</activatedProperties>
</properties>
</profile>
</profiles>
在pom文件裏分別配置好不同環境的文件名稱,注意:<activatedProperties>dev</activatedProperties>中的dev與配置文件名稱application-dev.properties要一致
activatedProperties名稱對應application.properties配置文件中的spring.profiles.active=@activatedProperties@
當maven打包時會用pom文件裏<activatedProperties>dev</activatedProperties>中的值替換掉application.properties配置文件中的@activatedProperties@
下面配置maven打包插件
<build>
<resources>
<resource>
<!--配置文件路徑 -->
<directory>src/resources</directory> <!--這裏對應項目存放配置文件的目錄-->
<!--開啓filtering功能 -->
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.2.RELEASE</version>
<configuration>
<mainClass>com.duan.SpringbootMybatis.App</mainClass><!--springboot啓動類目錄-->
</configuration>
<executions>
<execution>
<goals>
<!--創建一個自動可執行的jar或war文件 -->
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
配置完成,下面我們進行打包操作,我是使用eclipse進行打包,項目pom文件右鍵,run as ---> maven build
觀察控制檯輸入日誌
已經構建成功,刷新一下項目,target會生成SpringbootMybatis-0.0.1-SNAPSHOT.jar包。