1. 程式人生 >實用技巧 >其它 >SpringBoot多環境適配之道

SpringBoot多環境適配之道


技術標籤:java架構spring bootmaven

本文是應用配置中心的第三篇,第一篇介紹了配置演化之路,第二篇介紹了在傳統專案中以Maven作為多環境支援的方式。這篇將以SpringBoot為例,重點闡述在SpringBoot中如何適配多環境。

一、目錄如下

SpringBoot多環境適配之道

按照環境將配置檔案分開,比如,dev包含所有開發環境的配置資訊。

二、SpringBoot申明配置​​​​​​

# Spring配置spring:  # 模板引擎  thymeleaf:    mode: HTML    encoding: utf-8    # 禁用快取    cache: false  # 資源資訊  messages:    # 國際化資原始檔路徑    basename: i18n/messages  jackson:    time-zone: GMT+8    date-format: yyyy-MM-dd HH:mm:ss  profiles: active:@[email protected]這一句很重要

在SpringBoot中,使用profileActive進行申明,這個很重要。配合maven可以很輕鬆進行相關編譯打包。

三、pom.xml 配置簡化​​​​​​​

<!-- 多環境配置,dev:開發,test:測試,prod:生產-->  <profiles>    <profile>      <id>dev</id>      <properties>        <profileActive>dev</profileActive>      </properties>      <activation>          <!-- 預設情況下使用dev開發配置,如打包時不包含 -P 命令引數 -->        <activeByDefault>true</activeByDefault>      </activation>    </profile>    <profile>      <id>test</id>      <properties>        <profileActive>test</profileActive>      </properties>    </profile>    <profile>      <id>prod</id>      <properties>        <profileActive>prod</profileActive>      </properties>    </profile>  </profiles>

跟上一篇相比,maven的配置非常簡單,不再需要使用外掛的方式進行支援。

四、打包​​​​​​​

mvn clean package -Pdevmvn clean package -Ptest

通過執行maven的package打包命令,-P指定環境,即可實現預期目的。

以上就是SpringBoot中,如何應對多環境配置的適配解決方案。相對於傳統的Spring應用,SpringBoot做了非常巨大的精簡和優化,方便開發人員將精力集中到業務需求中。

希望文字對你有用,歡迎交流。

SpringBoot多環境適配之道