zl程序教程

您现在的位置是:首页 >  后端

当前栏目

使用Mavne生成可以执行的jar文件详解程序员

jar文件执行程序员 使用 详解 生成 可以
2023-06-13 09:20:19 时间

到目前为之,还没有运行HelloWorld的项目,不要忘了HelloWorld类可是有一个main方法的。使用mvn clean install命令默认生成的jar 包是不能直接运行的。因为带有main方法的类信息不会添加到manifest中(打开jar文件中的META-INFO/MANIFEST.MF文件,将无法看到Main-Class一行)。为了生成可以执行的jar文件,需要借助maven-shade-plugin,配置该插件如下:

 build 

 plugins 

 plugin 

 groupId org.apache.maven.plugins /groupId 

 artifactId maven-shade-plugin /artifactId 

 version 1.2.1 /version 

 executions 

 execution 

 phase package /phase 

 goals 

 goal shade /goal 

 /goals 

 configuration 

 transformers 

 transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer" 

 mainClass HelloWorld /mainClass 

 /transformer 

 /transformers 

 /configuration 

 /execution 

 /executions 

 /plugin 

 /plugins 

 /build 

plugin元素在POM中的相对位置在 project build plugins 下面。我们配置了mainClass为:HelloWorld,项目打包时会将该信息放到MANIFEST中。现在执行mvn clean install,待构建完成后打开target/目录,可以看到hellow-world-1.0-SNAPSHOT.jar,这个jar文件带有Main-Class信息的可运行jar,打开hellow-world-1.0-SNAPSHOT.jar的META-INFO/MANIFEST.MF,可以看到它包含这一行信息:

Main-Class: HelloWorld

现在在项目根目录中执行该jar文件:

java -jar hello-world-1.0-SNAPSHOT.jar

输出:

Hello World!!

 

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/6498.html

服务器部署程序员系统优化网站设置运维