把项目的配置文件按运行环境做一下区分,比如开发环境和线上环境使用的使用不同的配置文件,这里我们基于项目的 resoures/ 目录来实现:
# resoures 目录
.
├── env
│ ├── config.dev.properties
│ └── config.prod.properties
└── config.properties
我们创建了一个 config.properties 文件来配置项目的常用配置数据,如, kafaka 、 redis 等连接配置等。
然后创建一个 env 子目录,并创建两个环境对应的配置文件,我们希望不同的环境当中使用不同的配置。当然,光是创建这些文件,是无法让文件实现自动按照运行环境自动实现文件匹配的,我们还需要配置 pom.xml 文件:
首先,找到 <build> 配置字段,添加文件路径:
<build>
<!-- Loading all ${} -->
<filters>
<filter>src/main/resources/env/config.${env}.properties</filter>
</filters>
<!-- Map ${} into resources -->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>*.properties</include>
</includes>
</resource>
</resources>
<!-- 省略之后若干行 -->
</build>
上述代码目的是告诉构建工具,在构建的时候需要加载 resoures 目录的配置文件参与构建,并且使用 ${env} 环境变量来决定具体加载的名称。
因此,我们还需要指定 ${env} 的环境变量配置,在 <profiles> 标签下,移除默认的 <profile> 配置内容,新建两份环境配置 dev 和 prod 的 profile 文件配置:
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<!-- 省略若干 -->
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
<!-- 省略若干 -->
</profile>
</profiles>
如此,当我们运行项目时,可以根据不同的环境选择不同的配置文件,以保证开发和线上环境彻底分开,当然你也可以举一反三的创建测试环境、预上线环境等等。