如何用Maven、jLink和Launch4j生成独立于系统Java的.exe
问题描述
我尝试通过Maven将Jar文件打包为不依赖系统Java版本的EXE文件,已完成以下三步配置:
- 用maven-assembly-plugin打包包含所有依赖的Jar
- 用exec-maven-plugin调用jLink生成自定义JRE镜像
- 用launch4j-maven-plugin生成EXE文件
但目前生成的EXE仍依赖系统中的Java环境,如何调整配置让它仅依赖jLink生成的JRE镜像?
解决方案
核心问题在于路径配置错误和冗余的类路径设置,以下是具体修改点:
1. 调整jLink输出目录,让JRE与EXE同目录
当前jLink输出到target/jre,需改为输出到EXE所在的target/application/jre,确保打包后JRE与EXE处于同一目录,launch4j可通过相对路径找到它。修改exec-maven-plugin配置:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <executions> <execution> <id>jlink</id> <phase>package</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>jlink</executable> <arguments> <argument>--no-header-files</argument> <argument>--strip-debug</argument> <argument>--no-man-pages</argument> <argument>--compress=2</argument> <argument>--add-modules</argument> <argument>java.base,java.compiler,java.datatransfer,java.desktop,java.logging,java.management,java.naming,java.rmi,java.security.sasl,java.sql,java.xml</argument> <argument>--output</argument> <!-- 修改输出目录到application下的jre --> <argument>${project.build.directory}/application/jre</argument> </arguments> </configuration> </execution> </executions> </plugin>
2. 修改launch4j配置,使用相对路径并移除冗余类路径
移除classPath中的preCp配置(该配置会引入系统Java库),同时将jre/path改为相对路径jre,确保EXE启动时优先使用同目录的JRE:
<plugin> <groupId>com.akathist.maven.plugins.launch4j</groupId> <artifactId>launch4j-maven-plugin</artifactId> <executions> <execution> <id>l4j-clui</id> <phase>package</phase> <goals> <goal>launch4j</goal> </goals> <configuration> <headerType>console</headerType> <outfile>target\application\Sample.exe</outfile> <jar>target\jar-with-dependencies\Sample-jar-with-dependencies.jar</jar> <errTitle>encc</errTitle> <classPath> <mainClass>com.ge.Sample</mainClass> <!-- 移除preCp配置,避免加载系统Java库 --> </classPath> <jre> <!-- 使用相对路径,指向同目录下的jre --> <path>jre</path> <minVersion>17.0.6</minVersion> <requiresJdk>true</requiresJdk> <initialHeapSize>256</initialHeapSize> <maxHeapSize>1024</maxHeapSize> </jre> <versionInfo> <fileVersion>0.0.0.1</fileVersion> <fileDescription>a description</fileDescription> <copyright>Company</copyright> <productVersion>0.0.0.1</productVersion> <productName>E-N-C-C</productName> <internalName>ccne</internalName> <originalFilename>original.exe</originalFilename> </versionInfo> </configuration> </execution> </executions> </plugin>
3. 优化jLink模块依赖(可选)
用jdeps工具自动分析Jar依赖的模块,替换手动指定的--add-modules参数,可缩小JRE体积:
jdeps --list-deps target/jar-with-dependencies/Sample-jar-with-dependencies.jar
将输出的模块列表替换到jLink的--add-modules参数中即可。
验证方式
执行mvn clean package后,将target/application目录复制到未安装Java的系统中,运行Sample.exe,若能正常启动则配置生效。
内容的提问来源于stack exchange,提问作者Sepi
相关产品推荐
相关产品推荐

