使用maven profile实现多环境可移植构建

本文介绍如何通过Maven配置不同环境(开发、测试、生产)的profile,并实现特定环境的资源文件加载及构建过程。具体包括配置profile、定义配置文件目录及构建发布流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置profile

这里定义了三个环境,分别是development(开发环境)、test(测试环境)、production(生产环境),其中开发环境是默认激活的(activeByDefault为true),这样如果在不指定profile时默认是开发环境。
同时每个profile还定义了两个属性,其中profiles.active表示被激活的profile的名称,deploy.url表示发布服务器的地址。我们需要在下面使用到这两个属性。
另外host和port分别是发布服务器的主机地址和端口号。
首先是profile配置,在pom.xml中添加如下profile的配置:

    <profiles>
        <profile>
            <!-- 本地开发环境 -->
            <id>development</id>
            <properties>
                <profiles.active>development</profiles.active>
            </properties>

        </profile>
        <profile>
            <!-- 测试环境 -->
            <id>test</id>
            <properties>
                <profiles.active>test</profiles.active>
            </properties>
        </profile>
        <profile>
            <!-- 生产环境136 -->
            <id>production136</id>
            <properties>
                <profiles.active>production136</profiles.active>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <!-- 生产环境207 -->
            <id>production207</id>
            <properties>
                <profiles.active>production207</profiles.active>
            </properties>

        </profile>
    </profiles>
配置文件目录

针对不同的环境,我们定义不同的配置文件,而这些配置文件都做为资源文件放到maven工程的resources目录下,即src/main/resources目录下,且各个环境的配置分别放到相应的目录下,而所有环境都公用的配置,直接放到src/main/resources目录下即可。如下图所示:

这里写图片描述

maven资源插件配置

在pom中的build节点下,配置资源文件的位置,如下所示:

        <resources>  
            <resource>  
                <directory>src/main/resources</directory>  
                <!-- 资源根目录排除各环境的配置,使用单独的资源目录来指定 -->  
                <excludes>  
                    <exclude>test/*</exclude>  
                    <exclude>production136/*</exclude>
                    <exclude>production207/*</exclude>  
                    <exclude>development/*</exclude>  
                </excludes>  
            </resource>  
            <resource>  
                <directory>src/main/resources/${profiles.active}</directory>  
            </resource>  
        </resources>  

构建与发布

下图中根据发布需要更改activation的位置,如下加入我需要发布到生产环境136的服务器,那么activation的配置放在如下位置即可。
这里写图片描述
修改好activation的位置后,依次执行run as Maven clean—> run as Maven install
生产的war包会打印在console末尾,把war包上传到相应服务器即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值