maven打包 jar

最后更新时间: 2014年11月23日

1. maven-shade-plugin

2. maven-assembly-plugin

3. maven-onejar-plugin

maven-shade-plugin是我在ebay时前辈介绍给我的,我觉得它使用方便且没有出现过问题。但是我看别人的源代码,发现大家用的更多的是assembly,所以这里总结下这两种插件的用法。至于第三个,先留个坑在这,以后用到再总结。

使用插件maven-shade-plugin可以方便的将项目已jar包的方式导出,插件的好处在于它会把项目所依赖的其他jar包都封装起来,这种jar包放在任何JVM上都可以直接运行,我最初使用eclipse的maven-build直接打包,转移到intellij idea后没有这个按钮了,就只能用命令行搞了

使用步骤 :

将插件添加到pom.xml中,需要改的地方就是mainClass,在这里指定main方法的位置

使用mvn package打包,最后到projectName/target/下查找目标jar包

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>core.Test</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

Assembly 插件

pom.xml 文件

<!-- Maven Assembly Plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4.1</version>
                <configuration>
                    <!-- get all project dependencies -->
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <!-- MainClass in mainfest make a executable jar -->
                    <archive>
                      <manifest>
                        <mainClass>com.mkyong.core.utils.App</mainClass>
                      </manifest>
                    </archive>
 
                </configuration>
                <executions>
                  <execution>
                    <id>make-assembly</id>
                                        <!-- bind to the packaging phase -->
                    <phase>package</phase> 
                    <goals>
                        <goal>single</goal>
                    </goals>
                  </execution>
                </executions>
            </plugin>

使用步骤:

pom中添加插件依赖,命令行运行mvn package

目前,我对phase, goals, execution的理解还不够,不知道是什么意思

maven很是个很优秀的项目管理工具,是我在写C++代码时朝思暮想的东西,以后我还会用到它,尤其是项目之间依赖的maven解决方法,see you soon!

参考:

[1] Create A fat jar file - maven assembly plugin

原文地址:https://www.cnblogs.com/xinsheng/p/4109573.html