时间:2023-01-05 11:08:55 | 栏目:JAVA代码 | 点击:次
项目结构如下:
…/src/main/java/package/** <– application code
…/src/test/java/package/** <– test code
需求:
test中有一个包含main方法的主类TestMain.java,将main、test、全部依赖代码打包到一个jar包中,最终能通过java -jar的方式运行TestMain
这里Maven Jar Plugin 、 Maven Shade Plugin 都不是很适用。
我们选择Maven Assembly Plugin来打包
三步实现:
<project> ... <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.3</version> <configuration> <descriptor>src/main/assembly/assembly.xml</descriptor> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <archive> <manifest> <mainClass>com.sample.TestMain</mainClass> </manifest> </archive> </configuration> </execution> </executions> </plugin> ... </plugins> </build> <dependencies> ... </dependencies> </project>
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd"> <id>fat-tests</id> <formats> <format>jar</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <dependencySets> <dependencySet> <outputDirectory>/</outputDirectory> <useProjectArtifact>true</useProjectArtifact> <unpack>true</unpack> <scope>test</scope> </dependencySet> </dependencySets> <fileSets> <fileSet> <directory>${project.build.directory}/test-classes</directory> <outputDirectory>/</outputDirectory> <includes> <include>**/*.class</include> </includes> <useDefaultExcludes>true</useDefaultExcludes> </fileSet> </fileSets> </assembly>
在target目录下会生成一个xxxxx-1.0-SNAPSHOT-assembly.jar的文件,这就是我们需要的jar包了。我们可以用压缩软件看到生成的这个jar包中包含了test中所有的测试类。
可以直接使用java -jar xxxxx-1.0-SNAPSHOT-assembly.jar来运行jar包。主类就是第一步中设置的那个类
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> <configuration> <skipTests>true</skipTests> </configuration> </plugin>
mvn install -Dmaven.test.skip=true
或者
mvn install -DskipTests