maven多环境打包

来源:互联网 发布:马上6是什么软件 编辑:程序博客网 时间:2024/05/01 13:35

在开发过程中,我们的软件会面对不同的运行环境,比如开发环境、测试环境、生产环境,而我们的软件在不同的环境中,有的配置可能会不一样,比如数据源配置、日志文件配置、以及一些软件运行过程中的基本配置,那每次我们将软件部署到不同的环境时,都需要修改相应的配置文件,这样来回修改,是个很麻烦的事情。有没有一种方法能够让我们不用修改配置就能发布到不同的环境中呢?当然有,这就是接下来要做的事。

当然,这里的前提是使用maven做为构建工具。废话少复制的直接看配置。




<?xml version="1.0"?>

<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yangzhuang</groupId>
<artifactId>com.parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>com.yangzhuang.web</artifactId>
<packaging>war</packaging>
<name>com.yangzhuang.web</name>
<dependencies>
<dependency>
<groupId>com.yangzhuang</groupId>
<artifactId>com.yangzhuang.service</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
<build>
<filters>
<filter>src/main/resources/${env}/jdbc.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>

</project>


这是一个简单的多模块项目web模块中pom的中的多环境切换配置!其它就不贴出来了!!


1.profiles定义了各个环境的变量id

2.filters中定义了变量配置文件的地址,其中地址中的${env}环境变量就是上面profile中定义的值,定义了用哪个环境的文件做替换准备

3.resources中是定义哪些目录下的文件会被配置文件中定义的变量替换,一般我们会把项目的配置文件放在src/main/resources下,里面用到的变量在打包时就会根据filter中的变量配置替换成固定值

4:下面还有一种方式也可以用,我推荐用第一种,在pom里配置错了会给提示,你可以很方便的解决

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



原创粉丝点击