---
title: "maven多环境配置打包"
author: "Aaron5"
date: "2014-07-13T00:17:16Z"
tags: []
categories: ["研发管理"]
slug: "maven"
draft: false
lastmod: "2014-07-13T00:23:15Z"
id: 2091511
url: "https://clojure.iteye.com/blog/2091511"
---

项目开发经常碰到配置文件中测试的jdbc.url和线上的是不一样的。为此每次打包都要修改配置文件，很烦，而且也容易出错。

最近才发现，原来用maven的profile可以实现多种环境的配置。
配置过程如下：（具体例子可以下载[附件](http://dl.iteye.com/topics/download/3c2127df-1392-364a-8c70-5df4b2017278)）

1、在src/main/resources/filters，建两个文件：test.properties和prod.properties。
分别放置测试环境和生产环境的配置。（假设两个文件中都设置了jdbc.url属性）

2、新建src/main/resources/conf.properties文件。里面设置

```properties

jdbc.url=${jdbc.url}

```

3、配置pom.xml。配置如下

```pom.xml

<profiles>
        <profile>
            <id>test</id>
            <properties>
                <env>test</env>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <env>prod</env>
            </properties>
        </profile>
    </profiles>

    <build>
        <filters>
            <filter>src/main/resources/filters/${env}.properties</filter>
        </filters>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

```

4、打包。使用mvn packge -Ptest 即可实现测试环境打包。如果要prod环境配置，只需-Pprod即可。当然pom配置中默认不传-P参数的话是使用test环境配置。