将 Maven 项目打成可执行 Jar 包(包括相关的依赖)

使用 maven 的 maven-assembly-plugin 插件可以很方便的将项目打包成一个可执行 Jar 文件,下面以一个简单的 Spring 项目为例,讲述如何进行配置和打包。

项目结构

1582711842253

这是一个最简单的 Spring 项目,Test 类是包含 main 方法的入口,各文件内容如下:

Test.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.zhangzw;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.zhangzw.config.AppConfig;
import com.zhangzw.service.UserService;

public class Test {

public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.start();

UserService userService = context.getBean(UserService.class);
userService.query();
}
}

AppConfig.java

1
2
3
4
5
6
7
8
9
10
package com.zhangzw.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.zhangzw")
public class AppConfig {

}

UserService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.zhangzw.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

@Service
public class UserService {

private Log logger = LogFactory.getLog(this.getClass());

public void query() {
logger.info("hello");
}
}

log4j.properties

1
2
3
4
5
6
log4j.rootLogger=info,Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%d{HH:mm:ss SSS}] %5p %C:%L - %m%n

pom.xml 依赖

1
2
3
4
5
6
7
8
9
10
11
12
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>

插件 pom.xml 配置

插件配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<!-- 入口 main 方法所在类 -->
<mainClass>com.zhangzw.Test</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

打包和运行

使用 mvn package 命令打包,会在 target 目录下生成一个 test-1.0.0-jar-with-dependencies.jar 文件:

1582712543209

打开该文件里面包括了项目代码以及 maven 依赖的相关 Jar:

1582712393659

然后执行 java -jar test-1.0.0-jar-with-dependencies.jar 命令执行该可执行包,看输出结果表示可以正确运行项目:

1582712579515

参考

http://maven.apache.org/plugins/maven-assembly-plugin/