Java:使用maven将依赖打包进jar,执行jar

本文介绍如何使用Maven将项目的依赖库打包到一个单独的Jar文件中,以便于项目的部署和运行。通过在pom.xml中配置maven-assembly-plugin插件实现。

最近在用intellij IDEA创建maven项目的形式写些代码,依赖了一些库,通过pom.xml添加依赖解决。最终需要打包使用的时候,使用java命令运行其中的Class会报错,因为找不到依赖。

我在 http://stackoverflow.com/questions/1729054/including-dependencies-in-a-jar-with-maven 找到了解决方法。

可以通过添加一个插件来解决:

在pom.xml添加一个与<dependencies/>平级的节点:

    <build>
        <plugins>
            <!-- any other plugins -->
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>

如此,使用 mvn package打包,jar会在target目录中生成,然后用java命令执行就行了:

java -cp target/example-1.0-SNAPSHOT-jar-with-dependencies.jar  path.to.ExampleClass

转载于:https://my.oschina.net/letiantian/blog/804202

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值