使用的maven-resources-plugin来配置不同的环境,使用不同的资源来达到多环境打包的目的。
在src/main/resources目录下面,按照环境名称建立配置文件目录:
文件中引入maven-resources-plugin插件和相关的标签,引入pom文件部分说明
<profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <package.environment>dev</package.environment> </properties> </profile> <profile> <id>test</id> <properties> <package.environment>test</package.environment> </properties> </profile> <profile> <id>prod</id> <properties> <package.environment>prod</package.environment> </properties> </profile> </profiles> <build> <finalName>${project.artifactId}</finalName> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.xls</include> <include>**/*.xlsx</include> <include>**/*.png</include> <include>**/*.bpmn</include> <include>**/*.dtd</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.xsd</include> </includes> <excludes> <exclude>dev/*</exclude> <exclude>test/*</exclude> <exclude>prod/*</exclude> </excludes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${java.version}</source> <target>${java.version}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <!-- 不同环境的配置文件选择 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>copy-resources</id> <phase>compile</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <!-- 覆盖原有文件 --> <overwrite>true</overwrite> <outputDirectory>${project.build.outputDirectory}</outputDirectory> <!-- 也可以用下面这样的方式(指定相对url的方式指定outputDirectory) <outputDirectory>target/classes</outputDirectory> --> <!-- 待处理的资源定义 --> <resources> <resource> <!-- 指定resources插件处理哪个目录下的资源文件 --> <directory>src/main/resources/${package.environment}</directory> <filtering>false</filtering> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> </build>
为了不把多余的配置打到包里面,在红色部分这里进行了排除(不排除也可以,只有不引用相关的配置就可以)。
打包命令
mvn clean package mvn clean package -Pdev mvn clean package -Ptest mvn clean package -Pprod
执行命令,指定-P参数,启用指定的profile。