Maven项目实现多环境配置文件

在Spring boot项目中,我们已经习惯了多环境配置文件的使用。最近在维护旧项目时,因运行环境较多,一时起念,非Spring boot项目能实现多环境配置文件的配置和切换吗?经过查找资料,发现Maven早已提供了profile来实现多环境配置。真是孤陋寡闻,记录以学习之。


方式一:filter方式

  1. 编写多环境配置文件,分别定义主配置文件application.properties和两个环境配置文件application-dev.propertiesapplication-test.properties
  • application.properties
jdbc.username=${env.jdbc.username}
  • application-dev.properties
env.jdbc.username=dev
  • application-test.properties
env.jdbc.username=test

由上面文件中看到,我们在主配置文件并未定义实际值,而是引用环境配置中对应key的值。

  1. 在pom.xml中配置profile:
<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <env>dev</env>
        </properties>
        <activation>
        	<!-- 默认激活 -->
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>test</id>
        <properties>
            <env>test</env>
        </properties>
    </profile>
</profiles>

由上面文件中看到,我们配置了两套环境配置dev和test。

  1. 在pom.xml中配置filter和resource:
<build>
    <filters>
        <filter>src/main/resources/application-${env}.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

注意:<filtering>true</filtering>不可遗漏。

  1. 打包运行:
# 不指定运行环境,默认是activeByDefault=true的环境,当前是指开发环境
mvn package

# 指定运行环境,`<env>`指dev/test,注意参数P是大写
mvn package -P <env>

打包执行完成后,我们在target目录下的applincation.properties中可以看到值是随着指定运行环境变化的。

方式二:resource方式

  1. 在resources下建立多个环境目录放置各自的配置文件:
  • env/dev/application.properties
jdbc.username=dev
  • env/test/application.properties
jdbc.username=test
  1. 在pom.xml中配置profile:
<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <env>dev</env>
        </properties>
        <activation>
        	<!-- 默认激活 -->
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>test</id>
        <properties>
            <env>test</env>
        </properties>
    </profile>
</profiles>

由上可以看出,两种方式在这一步是一致的,区别主要在下一步。

  1. 在pom.xml中配置resource:
<build>
    <resources>
        <resource>
            <directory>${basedir}/src/resources/env/${env}</directory>
            <includes>
                <include>*/*.xml</include>
                <include>*/*.properties</include>
                <include>*.xml</include>
                <include>*.properties</include>
            </includes>
        </resource>
    </resources>
</build>
  1. 打包运行:
    和方式一一样的操作,打包后,可以看到只有一套配置文件出现在target目录里。

小结

  1. 方式一,会把多个环境的配置文件都打包进去,且主要针对属性文件,如果有多个文件或者其他类型文件,这种方式是不容易处理的;
  2. 方式二,只打包指定环境的配置文件,且会打包整个文件夹,更方便一点;
  3. 展开一下思路,Springboot其实是类似方式一的,如果Springboot项目想要只打包指定环境的配置文件,可以和方式二结合一下,一起处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值