最简单的基于Maven实现Sring Boot多环境配置和切换

最简单的基于Maven实现Sring Boot多环境配置和切换

在做Spring boot工程时,我们希望将那些需要区分环境的配置项挑出来,当idea中勾选了Profiles时,可以动态切换配置项。有两个实现方案:

方案一

听说Spring boot天生支持多环境的配置,具体配置方式如下:

  1. 分别创建开发、测试、线上环境的配置文件,文件名需要满足application-{profile}.properties的格式
  • application-dev.properties
  • application-test.properties
  • application-pro.properties
  1. 决定哪个配置生效,需要在application.properties中通过spring.profiles.active属性来设置

application.properties

spring.profiles.active=dev

完美收工!NO~
这不够智能,我们想在idea里勾选Profiles,然后自动切换环境配置,自动!自动!自动!
评价:

  • application-{profile}.properties里面放全量配置吗?其实区分环境的配置项可能很少,这会造成大量的冗余,很难保持这些冗余配置项的一致性。
  • application.properties里面只放一个激活配置,总感觉这不应该是它本来的面目。

方案二

其实可以结合Maven的filters更加优雅的实现自动切换环境

  1. 提取区分环境的配置项,放在resources/env/{profile}.properties,记住这里不是全量配置
datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
datasource.username=root
datasource.password=123456
  1. application.properties文件以变量的形式注入resources/env/{profile}.properties中的配置,这里使用${}不会生效,亲测@@可用
[email protected]@
[email protected]@
[email protected]@
  1. 使用profiles在pom中配置多环境
<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <profiles.active>dev</profiles.active>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>test</id>
        <properties>
            <profiles.active>test</profiles.active>
        </properties>
    </profile>
    <profile>
        <id>simulation</id>
        <properties>
            <profiles.active>simulation</profiles.active>
        </properties>
    </profile>
    <profile>
        <id>pro</id>
        <properties>
            <profiles.active>pro</profiles.active>
        </properties>
    </profile>
</profiles>
  1. 使用filters过滤出激活的配置
 <build>
    <filters>
        <filter>src/main/resources/env/${profiles.active}.properties</filter>
    </filters>
    <!--资源文件管理-->
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>env/*</exclude>
            </excludes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>application.properties</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

OK!现在勾选idea中的profile然后编译、打包是可以将不同环境的配置注入到application.properties中的。
评价:

  • 没有冗余不区分环境的配置
  • application.properties还是Spring Boot配置的主场所

以上,欢迎大家一起探讨学习~

发布了36 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Cmainlove/article/details/84033825