Java与Maven的打包操作
很久没有创建新的Spring Boot项目了,创建发现有报错 , 提示xxxjar中没有主清单属性, 这个错误表示在打包后的jar的META-INF/MANIFEST.MF文件中,没有配置Main-Class导致的,编译的依赖是Maven,也在项目中添加了spring-boot-maven-plugin的依赖,生成的MANIFEST.MF文件还是没有包含Main-Class,这就让我有点兴趣来研究下到底是怎么回事
1. 普通Jar命令生成的 MANIFEST.MF 文件
JAR的意思是Java Archive, 是Java程序的归档文件,包含了Class代码以及相关资源文件,可以同理为Zip格式,META-INF/MANIFEST.MF就是其中的头文件,包含了Jar包的基本信息,先看看Jar包是怎么生成的
- 生成普通Jar包
我们写一个Test.java文件来做测试
public class Test {
public static void main(String[] args){
System.out.println("hello world");
}
}
执行javac Test.java命令,生成Test.class文件
然后我们执行jar -cvf testjar Test.class命令,此时生成了test.jar文件,目录结构如下:
这个时候,我们看下MANIFEST.MF的文件内容如下:
Manifest-Version: 1.0
Created-By: 1.8.0_271 (Oracle Corporation)
-c表示创建jar包-
v表示输出创建信息
-f表示给生成的jar包命名
- 生成可执行jar包
这里面并没有包含Main-Class的内容,因为我们在打包Jar的时候没有指定主类,那我们看下Jar的命令参数(我在文末贴了详细的man jar命令说明),我们通过-e命令来指定哪个类是该jar包的主类
jar -cvfe test.jar Test.class *.class
**********输出如下*************
已添加清单
正在添加: Test.class(输入 = 413) (输出 = 287)(压缩了 30%)
这时MANIFEST.MF的文件内容多了一行Main-Class来指定启动类:
Manifest-Version: 1.0
Created-By: 1.8.0_271 (Oracle Corporation)
Main-Class: Test.class
2. 基于Maven的打包
- 普通Maven工程打包
创建maven普通工程
mvn archetype:generate -DgroupId=com.mario -DartifactId=maven-demo -Dversion=1.0 -DinteractiveMode=false
- 打包: mvn clean package -DskipTests
- 执行jar java -jar target/maven-demo-1.0.jar, 提示maven-demo-1.0.jar中没有主清单属性
- pom中添加依赖,先不指定启动类
<build> <plugins> <plugin> <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-jar-plugin --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.2.0</version> </plugin> </plugins> </build>
- 继续打包执行, 依然提示target/maven-demo-1.0.jar中没有主清单属性
- 添加<configuration> , 指定入口类
<plugin> <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-jar-plugin --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.2.0</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>com.mario.App</mainClass> </manifest> </archive> </configuration> </plugin>
- 再次打包运行,成功
Spring Boot工程打包
基于上面的工程,添加Spring Boot依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
修改App.java
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
SpringApplication.run(App.class, args);
}
}
- 打包, 看看MENIFEST.MF文件
Manifest-Version: 1.0 Class-Path: lib/spring-boot-starter-2.3.9.RELEASE.jar lib/spring-boot- 2.3.9.RELEASE.jar lib/spring-context-5.2.13.RELEASE.jar lib/spring-ao p-5.2.13.RELEASE.jar lib/spring-beans-5.2.13.RELEASE.jar lib/spring-e xpression-5.2.13.RELEASE.jar lib/spring-boot-autoconfigure-2.3.9.RELE ASE.jar lib/spring-boot-starter-logging-2.3.9.RELEASE.jar lib/logback -classic-1.2.3.jar lib/logback-core-1.2.3.jar lib/slf4j-api-1.7.25.ja r lib/log4j-to-slf4j-2.13.3.jar lib/log4j-api-2.13.3.jar lib/jul-to-s lf4j-1.7.30.jar lib/jakarta.annotation-api-1.3.5.jar lib/spring-core- 5.2.13.RELEASE.jar lib/spring-jcl-5.2.13.RELEASE.jar lib/snakeyaml-1. 26.jar Build-Jdk-Spec: 1.8 Created-By: Maven Jar Plugin 3.2.0 Main-Class: com.mario.App
- 执行,报错
Hello World! Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication at com.mario.App.main(App.java:16) Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication at java.net.URLClassLoader.findClass(URLClassLoader.java:382) at java.lang.ClassLoader.loadClass(ClassLoader.java:418) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355) at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ... 1 more
- 修改pom.xml,取消maven-jar-plugin依赖,新增spring-boot-maven-plugin 依赖
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.3.9.RELEASE</version> </plugin> </plugins> </build>
- 打包,查看MENIFEST.MF文件
Manifest-Version: 1.0 Archiver-Version: Plexus Archiver Built-By: mario Created-By: Apache Maven 3.6.3 Build-Jdk: 1.8.0_271
- 没有入口类,修改pom.xml, 添加executions配置
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.3.9.RELEASE</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
- 打包,查看MENIFEST.MF文件
Manifest-Version: 1.0 Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx Archiver-Version: Plexus Archiver Built-By: mario Start-Class: com.mario.App Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ Spring-Boot-Version: 2.3.9.RELEASE Created-By: Apache Maven 3.6.3 Build-Jdk: 1.8.0_271 Main-Class: org.springframework.boot.loader.JarLauncher
- 启动jar
mario@appledeMacBook-Pro ~/Dropbox/Inbox/test/maven-demo/maven-demo > java -jar target/maven-demo-1.0.jar Hello World! . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.9.RELEASE) 2021-03-24 15:40:40.254 INFO 79480 --- [ main] com.mario.App : Starting App on appledeMacBook-Pro.local with PID 79480 (/Users/mario/Dropbox/Inbox/Test/maven-demo/maven-demo/target/maven-demo-1.0.jar started by mario in /Users/mario/Dropbox/Inbox/Test/maven-demo/maven-demo) 2021-03-24 15:40:40.258 INFO 79480 --- [ main] com.mario.App : No active profile set, falling back to default profiles: default 2021-03-24 15:40:41.122 INFO 79480 --- [ main] com.mario.App : Started App in 1.499 seconds (JVM running for 2.092)
- 成功
参考文档: Spring Boot Maven Plugin Documentation
附录: JAR命令说明
NAME
jar - Java archive tool
SYNOPSIS
Create jar file
jar c[v0M]f jarfile [ -C dir ] inputfiles [ -Joption ]
jar c[v0]mf manifest jarfile [ -C dir ] inputfiles [ -Joption ]
jar c[v0M] [ -C dir ] inputfiles [ -Joption ]
jar c[v0]m manifest [ -C dir ] inputfiles [ -Joption ]
Update jar file
jar u[v0M]f jarfile [ -C dir ] inputfiles [ -Joption ]
jar u[v0]mf manifest jarfile [ -C dir ] inputfiles [ -Joption ]
jar u[v0M] [ -C dir ] inputfiles [ -Joption ]
jar u[v0]m manifest [ -C dir ] inputfiles [ -Joption ]
Extract jar file
jar x[v]f jarfile [ inputfiles ] [ -Joption ]
jar x[v] [ inputfiles ] [ -Joption ]
List table of contents of jar file
jar t[v]f jarfile [ inputfiles ] [ -Joption ]
jar t[v] [ inputfiles ] [ -Joption ]
Add index to jar file
jar i jarfile [ -Joption ]
PARAMETERS
cuxtivOMmf Options that control the jar command.
jarfile Jar file to be created (c), updated (u), extracted (x), or have its table of con-
tents viewed (t). The f option and filename jarfile are a pair -- if either is
present, they must both appear. Note that omitting f and jarfile accepts a "jar
file" from standard input (for x and t) or sends the "jar file" to standard output
(for c and u).
inputfiles Files or directories, separated by spaces, to be combined into jarfile (for c and
u), or to be extracted (for x) or listed (for t) from jarfile. All directories are
processed recursively. The files are compressed unless option O (zero) is used.
manifest Pre-existing manifest file whose name: value pairs are to be included in MANI-
FEST.MF in the jar file. The m option and filename manifest are a pair -- if
either is present, they must both appear. The letters m and f must appear in the
same order that manifest and jarfile appear.
-C dir Temporarily changes directories to dir while processing the following inputfiles
argument. Multiple -C dir inputfiles sets are allowed.
-Joption Option to be passed into the Java runtime environment. (There must be no space
between -J and option).
DESCRIPTION
The jar tool combines multiple files into a single JAR archive file. jar is a general-purpose
archiving and compression tool, based on ZIP and the ZLIB compression format. However, jar was
designed mainly to facilitate the packaging of Java applets or applications into a single ar-
chive. When the components of an applet or application (.class files, images and sounds) are
combined into a single archive, they can be downloaded by a Java agent (like a browser) in a sin-
gle HTTP transaction, rather than require a new connection for each piece. This dramatically
improves download time. The jar tool also compresses files, which further improves download
time. In addition, it allows individual entries in a file to be signed by the applet author so
that their origins can be authenticated. The syntax for the jar tool is almost identical to the
syntax for the tar(1) command. A jar archive can be used as a class path entry, whether or not
it is compressed.
Typical usage to combine files into a jar file is:
% jar cf myFile.jar *.class
In this example, all the class files in the current directory are placed in the file named
myjarfile. A manifest file entry named META-INF/MANIFEST.MF is automatically generated by the
jar tool and is always the first entry in the jar file. The manifest file is the place where any
meta-information about the archive is stored as name:value pairs. Refer to the Jar File specifi-
cation for details about how meta-information is stored in the manifest file.
If you have a pre-existing manifest file whose name: value pairs you want the jar tool to include
for the new jar archive, you can specify it using the m option:
% jar cmf myManifestFile myJarFile *.class
Be sure that any pre-existing manifest file that you use ends with a new line. The last line of a
manifest file will not be parsed if it doesn't end with a new line character. Note that when you
specify "cfm" instead of "cmf" (i.e., you invert the order of the "m" and "f" options), you need
to specify the name of the jar archive first, followed by the name of the manifest file:
% jar cfm myJarFile myManifestFile *.class
The manifest is in a text format inspired by RFC822 ASCII format, so it is easy to view and
process manifest-file contents.
To extract the files from a jar file, use x , as in:
% jar xf myFile.jar
To extract only certain files from a jar file, supply their filenames:
% jar xf myFile.jar foo bar
Beginning with version 1.3 of the Java 2 SDK, the jar utility supports JarIndex, which allows
application class loaders to load classes more efficiently from jar files. If an application or
applet is bundled into multiple jar files, only the necessary jar files will be downloaded and
opened to load classes. This performance optimization is enabled by running jar with the i
option. It will generate package location information for the specified main jar file and all the
jar files it depends on, which need to be specified in the Class-Path attribute of the main jar
file's manifest.
% jar i main.jar
In this example, an INDEX.LIST file is inserted into the META-INF directory of main.jar. The
application class loader will use the information stored in this file for efficient class load-
ing. Refer to the JarIndex specification for details about how location information is stored in
the index file.
A standard way to copy directories is to first compress files in dir1 to standard out, then
extract from standard in to dir2 (omitting f from both jar commands):
% (cd dir1; jar c .) | (cd dir2; jar x)
Examples of using the jar tool to operate on jar files and jar file manifests are provided below
and in the Jar trail of the Java Tutorial.
OPTIONS
c Creates a new archive file named jarfile (if f is specified) or to standard output (if f and
jarfile are omitted). Add to it the files and directories specified by inputfiles.
u Updates an existing file jarfile (when f is specified) by adding to it files and directories
specified by inputfiles. For example:
jar uf foo.jar foo.class
would add the file foo.class to the existing jar file foo.jar. The u option can also update the
manifest entry, as given by this example:
jar umf manifest foo.jar
updates the foo.jar manifest with the name: value pairs in manifest.
x Extracts files and directories from jarfile (if f is specified) or standard input (if f and
jarfile are omitted). If inputfiles is specified, only those specified files and directories
are extracted. Otherwise, all files and directories are extracted.
t Lists the table of contents from jarfile (if f is specified) or standard input (if f and
jarfile are omitted). If inputfiles is specified, only those specified files and directories
are listed. Otherwise, all files and directories are listed.
i Generate index information for the specified jarfile and its dependent jar files. For exam-
ple:
jar i foo.jar
would generate an INDEX.LIST file in foo.jar which contains location information for each package
in foo.jar and all the jar files specified in the Class-Path attribute of foo.jar. See the index
example.
f Specifies the file jarfile to be created (c), updated (u), extracted (x), indexed (i), or
viewed (t). The f option and filename jarfile are a pair -- if present, they must both
appear. Omitting f and jarfile accepts a "jar file" from standard input (for x and t) or
sends the "jar file" to standard output (for c and u).
v Generates verbose output to standard output. Examples shown below.
0 Zero. Store without using ZIP compression.
M Do not create a manifest file entry (for c and u), or delete a manifest file entry if one
exists (for u).
m Includes name: value attribute pairs from the specified manifest file manifest in the file
at META-INF/MANIFEST.MF. A name: value pair is added unless one already exists with the same
name, in which case its value is updated.
On the command line, the letters m and f must appear in the same order that manifest and jarfile
appear. Example use:
jar cmf myManifestFile myFile.jar *.class
You can add special-purpose name: value attribute pairs to the manifest that aren't contained in
the default manifest. Examples of such attributes would be those for vendor information, version
information, package sealing, and to make JAR-bundled applications executable. See the JAR Files
trail in the Java Tutorial and the Notes for Developers page for examples of using the m option.
-C Temporarily changes directories (cd dir) during execution of the jar command while process-
ing the following inputfiles argument. Its operation is intended to be similar to the -C
option of the UNIX tar utility. For example:
% jar uf foo.jar -C classes bar.classes
would change to the classes directory and add the bar.class from that directory to foo.jar. The
following command,
jar uf foo.jar -C classes . -C bin xyz.class
would change to the classes directory and add to foo.jar all files within the classes directory
(without creating a classes directory in the jar file), then change back to the original direc-
tory before changing to the bin directory to add xyz.class to foo.jar. If classes holds files
bar1 and bar2, then here's what the jar file would contain using jar tf foo.jar:
META-INF/
META-INF/MANIFEST.MF
bar1
bar2
xyz.class
Joption
Pass option to the Java runtime environment, where option is one of the options described on
the man page for the java application launcher, java(1). For example, -J-Xms48m sets the
startup memory to 48 megabytes. It is a common convention for -J to pass options to the
underlying virtual machine.
COMMAND LINE ARGUMENT FILES
To shorten or simplify the jar command line, you can specify one or more files that themselves
contain arguments to the jar command (except -J options). This enables you to create jar com-
mands of any length, overcoming command line limits imposed by the operating system.
An argument file can include options and filenames. The arguments within a file can be space-sep-
arated or newline-separated. Filenames within an argument file are relative to the current direc-
tory, not the location of the argument file. Wildcards (*) that might otherwise be expanded by
the operating system shell are not expanded. Use of the '@' character to recursively interpret
files is not supported. The -J options are not supported because they are passed to the launcher,
which does not support argument files.
When executing jar, pass in the path and name of each argument file with the '@' leading charac-
ter. When jar encounters an argument beginning with the character `@', it expands the contents of
that file into the argument list.
For example, you could use a single argument file named "classes.list" to hold the names of the
files:
% find . -name '*.class' -print > classes.list
Then execute the jar command passing in the argfile:
% jar cf my.jar @classes.list
An argument file can be passed in with a path, but any filenames inside the argument file that
have relative paths are relative to the current working directory, not the path passed in. Here's
such an example:
% jar @path1/classes.list
EXAMPLES
To add all the files in a particular directory to an archive (overwriting contents if the archive
already exists). Enumerating verbosely (with the "v" option) will tell you more information about
the files in the archive, such as their size and last modified date.
% ls
1.au Animator.class monkey.jpg
2.au Wave.class spacemusic.au
3.au at_work.gif
% jar cvf bundle.jar *
added manifest
adding: 1.au(in = 2324) (out= 67)(deflated 97%)
adding: 2.au(in = 6970) (out= 90)(deflated 98%)
adding: 3.au(in = 11616) (out= 108)(deflated 99%)
adding: Animator.class(in = 2266) (out= 66)(deflated 97%)
adding: Wave.class(in = 3778) (out= 81)(deflated 97%)
adding: at_work.gif(in = 6621) (out= 89)(deflated 98%)
adding: monkey.jpg(in = 7667) (out= 91)(deflated 98%)
adding: spacemusic.au(in = 3079) (out= 73)(deflated 97%)
If you already have separate subdirectories for images, audio files and classes, you can combine
them into a single jar file:
% ls -F
audio/ classes/ images/
% jar cvf bundle.jar audio classes images
added manifest
adding: audio/(in = 0) (out= 0)(stored 0%)
adding: audio/1.au(in = 2324) (out= 67)(deflated 97%)
adding: audio/2.au(in = 6970) (out= 90)(deflated 98%)
adding: audio/3.au(in = 11616) (out= 108)(deflated 99%)
adding: audio/spacemusic.au(in = 3079) (out= 73)(deflated 97%)
adding: classes/(in = 0) (out= 0)(stored 0%)
adding: classes/Animator.class(in = 2266) (out= 66)(deflated 97%)
adding: classes/Wave.class(in = 3778) (out= 81)(deflated 97%)
adding: images/(in = 0) (out= 0)(stored 0%)
adding: images/monkey.jpg(in = 7667) (out= 91)(deflated 98%)
adding: images/at_work.gif(in = 6621) (out= 89)(deflated 98%)
% ls -F
audio/ bundle.jar classes/ images/
To see the entry names in the jarfile, use the t option:
% jar tf bundle.jar
META-INF/
META-INF/MANIFEST.MF
audio/1.au
audio/2.au
audio/3.au
audio/spacemusic.au
classes/Animator.class
classes/Wave.class
images/monkey.jpg
images/at_work.gif
To add an index file to the jar file for speeding up class loading, use the "i" option.
Let's say you split the inter-dependent classes for a stock trade application, into three jar
files: main.jar, buy.jar, and sell.jar. If you specify the Class-path attribute in the main.jar
manifest as:
Class-Path: buy.jar sell.jar
then you can use the i option to speed up your application's class loading time:
% jar i main.jar
An INDEX.LIST file is inserted to the META-INF directory which will enable the application class
loader to download the specified jar files when it is searching for classes or resources.
SEE ALSO
The JAR Overview @
http://java.sun.com/javase/6/docs/technotes/guides/jar/jarGuide.html
The JAR File Specification @
http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html
The JARIndex Spec @
http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html
JAR Tutorial @
http://java.sun.com/docs/books/tutorial/jar/
pack200 Reference Page @
http://java.sun.com/javase/6/docs/technotes/tools/share/pack200.html
本文由博客群发一文多发等运营工具平台 OpenWrite 发布