在日常的开发中,我们的项目经常有几套环境,开发环境、测试环境、生产环境,就有几套配置文件,如果频繁修改配置文件难免容易出错。
maven提供了一套解决方案< profiles>标签。
**
**
1.配置文件路径
< profiles>
<!-- 本地开发环境 --> <profile> <!--执行打包命令时将使用此处的id进行定位 --> <id>dev</id> <properties> <!--此处为对应的环境放置配置文件的目录,上一步创建的为dev,这里设置为dev。下面两个目录配置参照此处 --> <env>dev</env> </properties> <activation> <!--此处将dev设置为默认环境 --> <activeByDefault>true</activeByDefault> </activation> </profile> <!-- 测试环境 --> <profile> <id>test</id> <properties> <env>test</env> </properties> </profile> <!-- 生产环境 --> <profile> <id>prod</id> <properties> <env>prod</env> </properties> </profile> </profiles>
3.在build节点中配置文件过滤器
< resources> <!--此处的设置是打包的时候排除不相关的目录 --> <resource> <!--此处设置为上面在resources目录下创建的文件夹 --> <directory>src/main/resources/env</directory> <excludes> <exclude>dev/*</exclude> <exclude>test/*</exclude> <exclude>prod/*</exclude> </excludes> <!--开启过滤器,此处不能忽略! --> <filtering>true</filtering> </resource> <!--此处的设置是为了将放置于resources文件夹下mybatis的mapper文件正常打包进去,和一些不需要多环境的配置文件 --> <resource> <!--如果将mybatis的mapper文件放在dao接口的同目录下,应该将此处设置为src/main/java --> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> </includes> <!--此处不需要过滤器过滤 --> <filtering>false</filtering> </resource> <!--此处设置是配置相应配置文件夹的路径 --> <resource> <directory>src/main/resources/env/${env}</directory> </resource> </resources>
4.配置打包插件
< plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <!--这里写上main方法所在类的路径 --> <configuration> <mainClass>com.travelsky.itwtcs.ItwApplication</mainClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins>
二、使用cmd进行打包
1.进入pom.xml所在目录下
运行cmd命令:mvn package -Pdev //dev表示你要打包的环境
运行命令后会在target下生成jar包,它主要是通过你配置的文件路径找到对应的文件并将它copy出来覆盖最外面的配置文件,达到更换配置的目的。
2.运行jar 进入target目录下 java -jar xxx.jar
三、每次都是用cmd去打包难免麻烦
1.创建并编写cmd脚本bat文件
@echo off
@echo ---------------------- testing environment ----------------------System jar file target
mvn package -Ptest
@pause
2.将bat文件放入pom.xml所在目录下,双击运行。
3.当我将bat文件copy到eclipse下去运行却报错,路径错误。
原来在eclipse中执行bat那么默认会是用eclipse的路径,而不是你项目文件夹路径,修改bat文件
@echo off
@echo ---------------------- testing environment ----------------------System jar file target
cd %~dp0
mvn package -Ptest
@pause
4.双击运行
5.成功