Maven profile 打包分环境加载不同的资源文件

在实际开发项目中,常常有几种环境,一般情况下最少有三种环境:开发测试正式。

各个环境之间的参数各不相同,比如mysql、等不同环境的host不一样,若每个环境都手动替换环境很容易出错,这里我们利用maven的profile功能切换环境。

项目结构如下

“dev” ---------------> 开发环境

“product”----------->生产环境          开发和生产加载不同的数据库配置文件  db.properties

 

pom.xml 如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/maven-v4_0_0.xsd">
<profiles>
        <profile>
            <id>dev</id>
            <properties>
                <env>dev</env>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>    <!-- 默认加载开发环境的配置文件-->
            </activation>
        </profile>
        <profile>
            <id>product</id>
            <properties>
                <env>product</env>
            </properties>
        </profile>
        <profile>
            <id>sandbox</id>
            <properties>
                <env>sandbox</env>
            </properties>
        </profile>
</profiles>

。。。。。。。。。。。。。。

<build>
        <finalName>ROOT</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    <plugins>
      <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <resourceEncoding>${project.encoding}</resourceEncoding>
                </configuration>
        </plugin>
。。。。。。。。。。。。
    </plugins>
  </build>

 

 

applicationContext.xml 配置如下

 ${env}  -----> 打包时传入对应的profiles id 就会加载对应的配置文件。

<context:property-placeholder ignore-resource-not-found="false" location="classpath:${env}/db.properties"/> 

 通过eclipse 打包, Profiles 输入product ,就会加载 product下的配置文件,默认的是开发环境(在pom的profiles中配置)

 

使用maven  命令

使用  mvn install -P{profile} 命令打包war
example:     
1、mvn install               没有指定profile,默认为dev
2、mvn install -Pdev -Dmaven.test.skip=true   指定profile为dev并跳过测试

 

域名购买.com 后缀好域名 

 https://mi.aliyun.com/shop/38040

 

posted @ 2017-12-01 16:09  咸鱼Boy  阅读(1318)  评论(0编辑  收藏  举报