Maven使用多环境配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/quuqu/article/details/79240839

在工作中,我们经常遇到多环境需要不同的配置文件,例如不同环境下连接的数据库不一致。
spring boot项目中可以较为方便的集成,那么在传统的spring web项目中应该如何解决这个问题呢,下面我们尝试使用maven的filter进行处理不同环境的变量值。

配置pom文件

  • 为pom文件添加profile的配置
 <profiles>
    <profile>
      <id>local</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <properties>
        <env>local</env>
      </properties>
    </profile>
    <profile>
      <id>development</id>
      <properties>
        <env>development</env>
      </properties>
    </profile>
    <profile>
      <id>test</id>
      <properties>
        <env>test</env>
      </properties>
    </profile>
    <profile>
      <id>production</id>
      <properties>
        <env>production</env>
      </properties>
    </profile>
  </profiles>

在本段代码中,我们将local设置为默认的环境变量,那么在我们打包的过程中如果不置顶环境变量,maven将按照默认的local形式进行打包。我们为每个profile设置了一个env的变量值,该值可以让我们在其他部分配置直接引用。

  • 配置filter
    <filters>
        <filter>src/main/resource/${env}/application.properties</filter>
    </filters>

通过filter,我们可以将不同环境目录下的application.properties文件中的参数值加载到maven中,如果我们有多个properties可以在添加一个filter即可。

  • 配置resources
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <excludes>
                    <exclude>local/*</exclude>
                    <exclude>development/*</exclude>
                    <exclude>test/*</exclude>
                    <exclude>production/*</exclude>
                </excludes>
            </resource>
        </resources>

通过指定filtering表示该目录下的文件都将通过maven的过滤进行变量值的替换,并且我们将源代码中的多环境目录进行排除,在maven编译生成的目录将不会带目录文件。

配置application.properties文件

在src/main/resources/目录下新建一个application.properties,并添加内容

test.properties=@test.properties@

此处的@test.properties@为通过fileter筛选各自环境下的加入到maven的变量值。
例如src/main/resources/production/applicaiton.properties文件内容为:

test.properties=production

maven在编译的过程中会替换 @test.properties@为production,最终生成的application.properties文件内容应该为:

test.properties=production

通过上面的讲解和代码配置,我们完成了maven多环境变量的配置工作,接下来我们来使用maven编译试试?

  • 通过命令进行打包
mvn clean compile  -Pproduction
  • 查看目录文件生成情况

image.png

常见问题

maven在替换变量的时候,默认 {]和@@表达式均可替换,如果我们在spring 的xml配置文件中使用 {} 也会被maven替换掉,为了避免该问题,我们可以参考spring boot的parent中的xml进行配置

 <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.6</version>
    <configuration>
    <delimiters>
    <delimiter>@</delimiter>
    </delimiters>
    <useDefaultDelimiters>false</useDefaultDelimiters>
    </configuration>
</plugin>

重点是delimiter的配置,该配置主要配置变量的分隔符,我们配置为@,那么它就不会对${}产生作用了,具体说明可以参考maven的官方文档 maven delimiters


结语

通过上面的展示,想必我们都已经学会使用maven的多环境配置了,本段的demo我也传到github上,大家可以自行查看具体源代 —– github源代码

猜你喜欢

转载自blog.csdn.net/quuqu/article/details/79240839
今日推荐