File tree Expand file tree Collapse file tree 1 file changed +99
-0
lines changed
Filter options
Expand file tree Collapse file tree 1 file changed +99
-0
lines changed
Original file line number Diff line number Diff line change
1
+ ## 如何使用maven把项目及其依赖打包为可运行jar包
2
+
3
+ #### 问题
4
+
5
+ 我想把java项目打包为可运行的分布式jar包。我该怎样做,才能把项目中maven所依赖的jar包导入到我的项目jar包中?
6
+
7
+ #### 回答
8
+
9
+ 在` pom.xml ` 文件中,加入如下的插件:
10
+
11
+ ``` xml
12
+ <build >
13
+ <plugins >
14
+ <plugin >
15
+ <artifactId >maven-assembly-plugin</artifactId >
16
+ <configuration >
17
+ <archive >
18
+ <manifest >
19
+ <!-- 这里是你的项目main函数所在的类的全限定名 -->
20
+ <mainClass >fully.qualified.MainClass</mainClass >
21
+ </manifest >
22
+ </archive >
23
+ <descriptorRefs >
24
+ <descriptorRef >jar-with-dependencies</descriptorRef >
25
+ </descriptorRefs >
26
+ </configuration >
27
+ </plugin >
28
+ </plugins >
29
+ </build >
30
+ ```
31
+
32
+ 之后,运行maven命令:
33
+
34
+ > mvn clean compile assembly: single
35
+
36
+ ` clean ` ,` compile ` ,` assembly:single ` 任务将会依次被执行;` compile ` 任务必须写在` assembly:single ` 之前,否则打包后的jar包内将不会有你的编译代码。
37
+
38
+ (译注:执行完后,会在你的maven项目的target目录下,生成想要的jar包,而不再需要使用` mvn package ` 命令进行打包)
39
+
40
+ 通常情况下,上述maven命令执行后会自动绑定到项目的构建阶段,从而保证了以后在执行` mvn install ` 命令时的jar包也会被构建。
41
+ (译注:下面是实际上完整的默认的` pom.xml ` 配置,只不过` <executions> ` 可以被省略,若省略则按照下述默认的配置执行)
42
+
43
+ ``` xml
44
+ <plugin >
45
+ <artifactId >maven-assembly-plugin</artifactId >
46
+ <configuration >
47
+ <archive >
48
+ <manifest >
49
+ <mainClass >fully.qualified.MainClass</mainClass >
50
+ </manifest >
51
+ </archive >
52
+ <descriptorRefs >
53
+ <descriptorRef >jar-with-dependencies</descriptorRef >
54
+ </descriptorRefs >
55
+ </configuration >
56
+ <executions >
57
+ <execution >
58
+ <id >make-assembly</id > <!-- 用于maven继承项目的聚合 -->
59
+ <phase >package</phase > <!-- 绑定到package阶段 -->
60
+ <goals >
61
+ <goal >single</goal >
62
+ </goals >
63
+ </execution >
64
+ </executions >
65
+ </plugin >
66
+ ```
67
+
68
+ #### 拓展
69
+
70
+ 怎样去运行打包后的可运行jar包?
71
+
72
+ * 对上述配置中已经指定了` main ` 函数所在类的jar包,打开命令行窗口,输入命令:
73
+
74
+ ``` java
75
+ java - jar jar包的路径/ jar包的名字. jar
76
+ ```
77
+
78
+ 例如:
79
+
80
+ ``` Auto
81
+ java -jar D:\my_java_project\maven_test.jar
82
+ ```
83
+
84
+ * 若在pom.xml并没有指定` main ` 方法所在类,那么该jar的运行应采取如下命令:
85
+
86
+ ``` java
87
+ java - cp jar包的路径/ jar包的名字. jar main方法所在类的全限定名
88
+ ```
89
+
90
+ 例如:
91
+
92
+ ``` java
93
+ java - cp D : \my_java_project\maven_test. jar com.my.path. MainClass
94
+ ```
95
+
96
+
97
+ #### StackOverflow地址
98
+
99
+ [ http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven ] ( http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven )
You can’t perform that action at this time.
0 commit comments