在实际开发过程中,经常要在自己的本机上切换不同的配置文件进行打包,有的直接修改同一个配置文件,这样做不仅有修改风险,还比较累,最近搞了一下在eclipse环境中进行多环境配置的打包方式,让我和同事们轻松应对多环境打包。
配置: maven ,eclipse
一般地,我们的项目结构是这样的
现在需要改成这样子,举例说明一下:在resources目录下增加两个子目录(你有几个环境就增加几个目录),product应对线上环境,test应对测试环境,将配置文件复制到各目录下一份(其实有公共部分的文件可以单独提取出来,这里暂时不讨论),配置文件里的内容根据各自环境修改不同的值,这里就不截图了。
打开项目的pom.xml 文件,首先加入profiles节点
<profiles>
<profile>
<id>product</id>
<properties>
<package.environment>product</package.environment>
</properties>
</profile>
<profile>
<id>test</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<package.environment>test</package.environment>
</properties>
</profile>
</profiles>
解释:声明了两个profile,分别包含各自的properties属性定义,其中一个id为test的profile是默认的
再到build节点下增加 resources子节点
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>test/*</exclude>
<exclude>product/*</exclude>
</excludes>
</resource>
</resources>
解释:资源目录是src/main/resources,其中不包含test,product目录下的任何文件,为什么不包含,因为下面要分别设置
同在build节点中,在plugins子节点中,增加子节点
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
</archive>
<webResources>
<resource>
<directory>src/main/resources/${package.environment}</directory>
<targetPath>WEB-INF/classes</targetPath>
</resource>
</webResources>
</configuration>
</plugin>
解释:这是一个maven的war插件,定义资源目录是src/main/resources/${package.environment},这个${package.environment}就是要看具体哪个profile激活,就用那个profile里的定义的package.environment变量,资源文件打包目标路径是WEB-INF/classes目录下。
之所以在上面要屏蔽所有的子资源目录,就是不要把其他profile定义的资源文件也同时打包到目标路径。
----打包----
这时候我们可以项目右键->run as->maven install,因为我们设置了默认proflie为test,所以install完成后,classes目录下生成的文件,就是test目录下的。
如果这时候,我们需要打一个product(生成环境)的包,可以有两个方式来处理
1、简单粗暴:
直接把profiles里定义的默认值设置,剪切到product的profile里,然后项目右键->run as->maven install即可
<activation>
<activeByDefault>true</activeByDefault>
</activation>
2、文艺的对话框:
项目右键->run as->maven build...,打开maven命令对话框,在goals栏目中输入install,在profiles栏目中,输入product,执行即可。注意,这个命令可以在:项目右键->run as->maven build(注意没有省略号)里重复使用
看看生成的war包吧,Good Luck!!
如果哪里没有说清楚,或者不对的地方请各路大神指出,不胜感激。谢谢