使用maven profile指定配置文件打包适用多环境

新建maven项目,   在pom.xml中添加 profile节点信息如下:

<profiles>
        <profile>
            <!-- 开发环境 -->
            <id>dev</id>
            <properties>
                <environment>development</environment><!-- 节点名字environment是自己随意取的 -->
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault><!-- 默认激活该profile节点-->
            </activation>
        </profile>

        <profile>
            <!-- 测试环境 -->
            <id>test</id>
            <properties>
                <environment>test</environment>
            </properties>
        </profile>
        <profile>
            <!-- 生产环境 -->
            <id>prod</id>
            <properties>
                <environment>production</environment>
            </properties>
        </profile>

    </profiles>
View Code

二、在项目中添加各环境需要的各种配置文件,分不同目录存放, 分别是开发,测试, 生产 环境. 如下图左边部分所示

三、配置resource信息用来排除不需要的配置文件

 1 <resources>
 2             <resource>
 3                 <directory>src/main/resources</directory>
 4                 <excludes>
 5                     <exclude>development/*</exclude>
 6                     <exclude>test/*</exclude>
 7                     <exclude>production/**</exclude>
 8                 </excludes>
 9             </resource>
10             <resource>
11                 <directory>src/main/resources/${environment}</directory>
12                 <targetPath>${environment}</targetPath>
13             </resource>
14         </resources>
View Code

<directory>src/main/resources</directory>

<!--打包时包含src/main/resources目录下所有"子"文件 和 "孙"文件.如config 和environment -->

 

<exclude>development/**</exclude>

<!--打包时排除src/main/resources/development下所有"子"文件 和 "孙"文件.-->

 

<exclude>test/**</exclude>

<!--打包时排除src/main/resources/test下所有"子"文件 和 "孙"文件.-->


<exclude>production/**</exclude>

<!--打包时排除src/main/resources/production下所有"子"文件 和 "孙"文件.-->


<!-- 注意点: 如果写一个心号*, 如<exclude>development/*</exclude> 则表示:打包时排除src/main/resources/development下所有"子"文件, 不排除"孙"文件 -->
<!-- 以上配置优先度从上到下 递增, 这就达到目的: config目录下的配置各环境都需要, 而其它环境相关的配置只会有一个目录被打包--->

<directory>src/main/resources/${environment}</directory>

<!-- 打包时包含src/main/resources/${environment}下所有"子"文件,environment变量值来自profile中赋值 -->


<targetPath>${environment}</targetPath>

<!--指定src/main/resources/${environment}所有"子文件" 打包 到包的哪个目录 -->

四、项目打包.

打包命令mvn package -Pdev来指定激活id为 dev 的profile节点, 这样, 开发环境配置文件就会被打包.
开发: mvn package -Pdev (因为配置了默认激活dev部分, 所以也可以使用mvn package, 这与 mvn package -Pdev 效果相同)
测试: mvn package -Ptest
预演:mvn package -Pprev
生产:mvn package -Pprod

猜你喜欢

转载自www.cnblogs.com/hollowcabbage/p/9021647.html