SpringBoot多环境适配之道

本文是应用配置中心的第三篇,第一篇介绍了配置演化之路,第二篇介绍了在传统项目中以Maven作为多环境支持的方式。这篇将以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: @profileActive@   这一句很重要

在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做了非常巨大的精简和优化,方便开发人员将精力集中到业务需求中。

希望文字对你有用,欢迎交流。

图片

Guess you like

Origin blog.csdn.net/yelangkingwuzuhu/article/details/113396680