欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用 Maven 打包依赖于本地 jar 包的可执行 jar 包

最编程 2024-07-18 14:37:34
...

背景

这两天打包一个Maven工程,这个工程同时依赖了:

  • Maven*仓库的包
  • 本地的jar包
  • JetBrains GUI Designer 生成的 form 文件
    打包的时候遇到了一点麻烦,抛出各种class未定义的异常,折腾了一会,最后发现处理的方式比较简单,不需要像这篇博客里加好几个插件。

解决方法

如果我的项目依赖了项目根目录/lib/yyy.jar这个包,Maven打包的时候不会把这个包加到依赖里面的,首先要把这个jar包声明在pom.xml中:

    <dependency>
            <groupId>xxx.xxxx</groupId>
            <artifactId>yyy</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/yyy.jar</systemPath>
        </dependency>

记得替换上面的xxx和yyy。

然后在 pom.xml 中添加插件 maven-assembly-plugin

<build>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
               
                <!-- ... -->

                <plugin>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>cn.edu.cqu.graphics.ui.Entrance</mainClass>
                            </manifest>
                        </archive>
                        <descriptors>
                            <descriptor>src/assembly/package.xml</descriptor>
                        </descriptors>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>

然后在项目的 src/assembly目录下添加一个descriptor文件package.xml

<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.1.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.1.0 http://maven.apache.org/xsd/assembly-2.1.0.xsd">
    <id>jar-with-dependencies</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <useProjectArtifact>true</useProjectArtifact>
            <unpack>true</unpack>
            <scope>runtime</scope>
        </dependencySet>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <unpack>true</unpack>
            <scope>system</scope>
        </dependencySet>
    </dependencySets>
</assembly>

上面的配置跟https://maven.apache.org/plugins/maven-assembly-plugin/descriptor-refs.html
里的jar-with-dependencies配置相比,多出了以下内容:

        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <unpack>true</unpack>
            <scope>system</scope>
        </dependencySet>

作用就是把system scope的依赖项加进去。

完成了以上配置后,运行:

mvn clean compile assembly:single -e

就可以打包成功了。

关于 IntelliJ IDEA GUI Designer 的form文件依赖

我觉得最靠谱的方式还是让IDE生成Java代码:


image.png

设置成 Java Source Code后运行一下,就会自动生成form文件对应的Java代码。