通常,项目在生产环境跟开发环境中,配置参数多少会有一点差异,比如:日志路径、数据库地址等等。所以每次打生产环境的包,需要修改一些配置文件,如果手工修改配置文件的话,就太浪费人力物力,而且还容易手滑改错。
实际开发中需要根据不同环境将资源分别存放,构建部署包的时候,利用maven-resources-plugin插件和profiles命令将差异化的资源文件以及公共的资源文件复制到resources目录下即可。
先上代码,后面做详细解释
<profiles>
<profile>
<id>dev</id>
<properties>
<package.environment>dev</package.environment>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<package.environment>test</package.environment>
</properties>
</profile>
<profile>
<id>product</id>
<properties>
<package.environment>product</package.environment>
</properties>
</profile>
</profiles>
<build>
<finalName>demo</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>dev/**</exclude>
<exclude>product/**</exclude>
<exclude>test/**</exclude>
<exclude>common/**</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
</archive>
<warName>demo</warName>
<webResources>
<resource>
<directory>src/main/resources/${package.environment}</directory>
<targetPath>WEB-INF/classes</targetPath>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources/common</directory>
<targetPath>WEB-INF/classes</targetPath>
<filtering>true</filtering>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>
1、配置profiles
详细解释大家可以自行google,简单来说profile可以让定义一系列的配置信息,然后指定其激活条件。
上述代码profiles节点中,定义了三种环境:dev、test、product。
2、新建四个文件夹用来存放不同环境的资源环境
common:存放公共的资源文件
dev:存放开发环境资源文件
test:存放测试环境资源文件
product:存放生产环境资源文件
3、配置打包时候忽略新建的四个目录
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>dev/**</exclude>
<exclude>product/**</exclude>
<exclude>test/**</exclude>
<exclude>common/**</exclude>
</excludes>
</resource>
</resources>
exclude配置规则:
The mapping matches URLs using the following rules:
* matches zero or more characters (匹配0个或N个字符)
** matches zero or more directories in a path (匹配0个或N个目录)
在此要忽略目录下面的所有文件,所以配置test/**
4、配置maven-resources-plugin插件
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
</archive>
<warName>demo</warName>
<webResources>
<resource>
<!-- 指定resources插件处理哪个目录下的资源文件 -->
<directory>src/main/resources/${package.environment}</directory>
<!--默认是${build.outputDirectory}指定的目录 -->
<targetPath>WEB-INF/classes</targetPath>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources/common</directory>
<targetPath>WEB-INF/classes</targetPath>
<filtering>true</filtering>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
激活不同的profile,package.environment会有不同的值,会去相应的目录copy资源。
配置完成。
执行maven命令,以生产环境为例: