原文:https://blog.csdn.net/duan9421/article/details/79086335
我們在日常開發工作中通常會根據不同的項目運行環境,添加不同的配置文件,例如 開發環境,測試環境,生產環境等,每次手工的修改配置文件太過於繁瑣。通過maven打包時確定需要使用的配置文件可以很好的解決這個問題。
下面看一下代碼目錄
application-dev.properties對應開發環境
application-test.properties對應測試環境
application-prod.properties對應生產環境
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包。
我們可以觀察一下jar包的目錄結構:
打開manifest.mf文件
查看啟動類是否正確。
下面我們執行一下這個jar包,輸入執行命令,java -jar
出現啟動成功信息,對應端口號是8888與我們application-prod.properties配置文件中的一致,說明配置成功了。
瀏覽器訪問一下
訪問成功!
主要利用了maven打包時,攔截配置文件使用pom文件中的值替換掉spring.profiles.active=@activatedProperties@中的變量,完成動態配置文件的使用功能。
--------------------- 本文來自 夏日小蟲 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/duan9421/article/details/79086335?utm_source=copy