How to create a jar file with Maven

Java技术变现新路径:基于JVM生态的工程化赚钱模型 Java作为一门成熟语言,其核心价值已从语法特性升维为JVM生态所承载的稳定性、向后兼容性与企业级信任背书。在等保合规、遗留系统现代化和垂直领域工具链等刚性需求驱动下,Java凭借字节码增强、Java Agent、ClassLoader热加载等原生能力,成为构建合规即服务(Compliance-as-a-Service)、遗留系统缝合层及微型SaaS的关键技术底座。它不追求性能极限,而以‘可审计、可验证、零改造集成’满足法务签字、运维背书与终端用户习惯三重决策节点。本文聚焦Java在2025年中小企业技术变 阅读详情

In this tutorial, we will show you how to use Maven build tool, to create a single executable Jar, and how to deal with the project’s dependencies.

Tools used :

  1. Maven 3.1.1
  2. JDK 1.7
  3. log4j 1.2.17
  4. Joda-time 2.5
  5. Eclipse 4.3

1. Create a simple Java project

Create a Java project from the Maven quick start template.

$ mvn archetype:generate -DgroupId=com.mkyong.core.utils -DartifactId=dateUtils 
 -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

The following files and folder structure will be created.

.
|____dateUtils
| |____pom.xml
| |____src
| | |____main
| | | |____java
| | | | |____com
| | | | | |____mkyong
| | | | | | |____core
| | | | | | | |____utils
| | | | | | | | |____App.java
| | |____test
| | | |____java
| | | | |____com
| | | | | |____mkyong
| | | | | | |____core
| | | | | | | |____utils
| | | | | | | | |____AppTest.java

Above folder structure is not enough, create a log4j.properties file and put it in src/main/resources/log4j.properties, just create the resources folder manually.

log4j.properties
# Root logger option
log4j.rootLogger=DEBUG, stdout
 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

Make it support Eclipse.

$ mvn eclipse:eclipse

And imports the project into Eclipse IDE, the final project structure should be like this :

maven-create-a-jar

2. Update Pom.xml

Update pom.xml to declare both log4j and the jodatime dependencies, for output to a jar format, make sure the packaging is set to “jar”. Read below comment for self-explanatory.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
	http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mkyong.core.utils</groupId>
	<artifactId>dateUtils</artifactId>
	
	<!-- Output to jar format -->
	<packaging>jar</packaging>
	
	<version>1.0-SNAPSHOT</version>
	<name>dateUtils</name>
	<url>http://maven.apache.org</url>

	<properties>
		<jdk.version>1.7</jdk.version>
		<jodatime.version>2.5</jodatime.version>
		<junit.version>4.11</junit.version>
		<log4j.version>1.2.17</log4j.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>${jodatime.version}</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>dateutils</finalName>
		<plugins>

			<!-- download source code in Eclipse, best practice -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>false</downloadJavadocs>
				</configuration>
			</plugin>

			<!-- Set a JDK compiler level -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>

			<!-- Make this jar executable -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
				  <!-- DO NOT include log4j.properties file in your Jar -->
				  <excludes>
					<exclude>**/log4j.properties</exclude>
				  </excludes>
				  <archive>
					<manifest>
						<!-- Jar file entry point -->
						<mainClass>com.mkyong.core.utils.App</mainClass>
					</manifest>
				  </archive>
				</configuration>
			</plugin>

		</plugins>
	</build>

</project>

3. Update App.java

Update the generated App.java with the following content :

App.java
package com.mkyong.core.utils;

import org.apache.log4j.Logger;
import org.joda.time.LocalDate;

public class App {

	private static final Logger logger = Logger.getLogger(App.class);

	public static void main(String[] args) {
		System.out.println(getLocalCurrentDate());
	}

	private static String getLocalCurrentDate() {

		if (logger.isDebugEnabled()) {
			logger.debug("getLocalCurrentDate() is executed!");
		}

		LocalDate date = new LocalDate();
		return date.toString();

	}

}

Now, this project has two dependencies : log4j and jodatime.

4. Working with Dependencies

4.1. How can I add dependencies in a jar?

– You can put both log4j.jar and jodatime.jar inside the final.jar, but your classes are unable to call other classes which is inside the unpack log4j.jar, Java jar is designed like this, unless you create a special class loader like one-jar plugin.

– Alternatively, use maven-assembly-plugin to extract all dependency jars into raw classes, and group it together. Read thisStackOverflow thread. This hack is workable in project with less dependencies only, for large project with many dependencies, it will cause Java class name conflict issue.

– Try one-jar plugin, it will create a fat-jar, which includes the entire project’s dependencies into a single jar file, read this article – Create a fat Jar file with Maven

4.2 Solution
The one-jar solution is really good, but I don’t like the custom class loader and fat-jar concept. My simplest and always working solution is copy the entire project’s dependencies to a pre-defined folder, and define the dependency classpath in the jar’s manifest file.

Below is the updated and final pom.xml, to use maven-dependency-plugin to copy all dependencies totarget/dependency-jars/ folder, and use maven-jar-plugin to add the dependency classpath.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
	http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mkyong.core.utils</groupId>
	<artifactId>dateUtils</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>dateUtils</name>
	<url>http://maven.apache.org</url>

	<properties>
		<jdk.version>1.7</jdk.version>
		<jodatime.version>2.5</jodatime.version>
		<junit.version>4.11</junit.version>
		<log4j.version>1.2.17</log4j.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>${jodatime.version}</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>dateutils</finalName>
		<plugins>

			<!-- download source code in Eclipse, best practice -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>false</downloadJavadocs>
				</configuration>
			</plugin>

			<!-- Set a compiler level -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>

			<!-- Make this jar executable -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
				  <excludes>
					<exclude>**/log4j.properties</exclude>
				  </excludes>
				  <archive>
				    <manifest>
					<addClasspath>true</addClasspath>
					<mainClass>com.mkyong.core.utils.App</mainClass>
					<classpathPrefix>dependency-jars/</classpathPrefix>
				    </manifest>
				  </archive>
				</configuration>
			</plugin>

			<!-- Copy project dependency -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>2.5.1</version>
				<executions>
				  <execution>
					<id>copy-dependencies</id>
					<phase>package</phase>
					<goals>
						<goal>copy-dependencies</goal>
					</goals>
					<configuration>
					  <!-- exclude junit, we need runtime dependency only -->
					  <includeScope>runtime</includeScope>
					  <outputDirectory>${project.build.directory}/dependency-jars/</outputDirectory>
					</configuration>
				  </execution>
				</executions>
			</plugin>

		</plugins>
	</build>

</project>

5.The final Jar file

5.1 Package the project.

$ mvn package

Review the folder structure in the target folder

maven-create-jar-dependency-jars

A dateutils.jar is created, and the entire project runtime dependencies (excluded junit) are copied totarget/dependency-jars/ folder.

5.2 List out the dateutils.jar content :

$ jar tf target/dateutils.jar 
META-INF/
META-INF/MANIFEST.MF
com/
com/mkyong/
com/mkyong/core/
com/mkyong/core/utils/
com/mkyong/core/utils/App.class
META-INF/maven/
META-INF/maven/com.mkyong.core.utils/
META-INF/maven/com.mkyong.core.utils/dateUtils/
META-INF/maven/com.mkyong.core.utils/dateUtils/pom.xml
META-INF/maven/com.mkyong.core.utils/dateUtils/pom.properties

5.3 Extracts and review the content of MANIFEST.MF, the dependencies are added in the Class-Path.

META_INF/MANIFEST.MF
Manifest-Version: 1.0
Built-By: mkyong
Build-Jdk: 1.7.0_05
Class-Path: dependency-jars/joda-time-2.5.jar dependency-jars/log4j-1.2.17.jar
Created-By: Apache Maven 3.1.1
Main-Class: com.mkyong.core.utils.App
Archiver-Version: Plexus Archiver

5.4 Run it

$ java -jar target/dateutils.jar 

log4j:WARN No appenders could be found for logger (com.mkyong.core.utils.App).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
2014-10-19

Oppss…

5.5 Where is log4j.properties?
This is a GOOD practice to exclude the log4j.properties in the jar file, to avoid issues like multiple log4j.propertiesfiles in classpath.

You can still pass in the log4j properties via the log4j.configuration system property like this :

$ java -jar -Dlog4j.configuration=file:/full_path/log4j.properties target/dateutils.jar 

17:09:15,385 DEBUG App:18 - getLocalCurrentDate() is executed!
2014-10-19														
Note
In future, if you want to move  dateUtils.jar, make sure to copy its  dependency-jars folder as well. If you have a better idea, do share with me, thanks.

Done.

一点总结:maven-assembly-plugin 插件配置jar-with-dependencies 时,会将所有依赖的jar解压,有时候这个功能会有用。


TRAE:上下文感知型编程协作者原理与实战 在AI编程工具泛滥的今天,'上下文感知'正成为区分真智能与伪补全的核心技术分水岭。其本质是通过AST解析、多源配置扫描与语义图谱融合,实现对项目结构、依赖关系和开发意图的动态建模;技术价值在于将传统‘代码生成’升级为‘意图协商’,显著降低认知负荷与上下文切换成本;典型应用场景包括Java/Spring Boot项目中的自动接口推导、MySQL表结构联动编码、SSH远程配置同步等工程闭环;本文深入解析TRAE所代表的CUE-Context Understanding Engine架构,结合Tab-Cue交互范 阅读详情

相关推荐

GitHub Copilot CLI:终端智能代理工作流实战指南

终端智能代理(Terminal Intelligent Agent)是现代开发者工作流升级的核心范式,它超越传统命令行补全与脚本生成,通过上下文感知、任务规划与多模型协同,实现从‘手动执行’到‘意图驱动’的跃迁。其技术原理基于实时项目上下文注入(MCP协议)、轻量级任务图谱构建与模型即服务(MaaS)动态路由,在Shell自动化、CI/CD故障诊断、跨仓库同步等场景中显著降低认知负荷与操作熵。本文聚焦GitHub Copilot CLI这一典型实现,详解其作为可理解、可规划、可执行、可回溯的终端智能代理,在

weixin_30500473的博客 434

How to create a manifest file with Maven

This tutorial will show you how to use the maven-jar-plugin to create a manifest file, and package / add it into the final jar file. The manifest file is normally used to define following tasks :Defin...

orichisonic的专栏 421

Ambari3.0集成Flink 2.2+Paimon1.4

Ambari 3.0集成Flink 2.2+Paimon1.4

docsz的博客 681

Create a fat Jar file – Maven Assembly Plugin

Create a fat Jar file – Maven Assembly Plugin Posted on October 21, 2014 ,     Last modified : October 21, 2014 By mkyong In this tutorial, we will show yo

nobody 1743

Ambari3.0集成Flink 1.20+Paimon1.4

Ambari3.0集成Flink1.20+Paimon1.4

docsz的博客 214

Spark TPC-DS/H Data Gen

Data Gen

zhixingheyi_tian的博客 1505

Create a fat Jar file – Maven Shade Plugin

Create a fat Jar file – Maven Shade Plugin Posted on September 22, 2014 ,     Last modified : October 21, 2014 By mkyong In this tutorial, we will show you

nobody 1840

智能座舱-语音交互系统

从什么是智能座舱、智能座舱的发展驱动因素、智能座舱的构成要素三个方面梳理我对智能座舱的基础认识之后,为了加深“智能座舱产品入门”课程中语音交互部分知识的理解,我从什么是语音交互、语音交互的底层技术、智能座舱的语音交互等方面,对智能座舱语音交互系统相关的知识进行了梳理与总结。

GUOSA0928的博客 1442

Maven – Create a fat Jar file – One-JAR example

http://www.tuicool.com/articles/326JvaU In this tutorial, we will show you how to use Maven build tool, One-JAR plugin to create a single Jar together with its dependency Jars into a

lsyangmx600的博客 380

从零开始:如何在Windows上搭建Airsim仿真环境(避坑指南)

本文是一份详细的Windows平台AirSim仿真环境搭建指南。文章从硬件要求、Visual Studio与虚幻引擎安装开始,逐步讲解AirSim插件编译、UE项目配置,并重点介绍了通过WSL2连接PX4飞控软件实现软件在环仿真的完整流程。内容涵盖常见问题排查与性能优化,旨在帮助开发者避开常见陷阱,高效构建可用于无人机算法开发的虚拟测试平台。

earth的博客 301

从零开始的 AI Infra 学习之路

AI Infra(AI 基础设施)是指为上层的 AI 算法应用提供支持的 AI 全栈底层技术,通过合理利用计算机体系结构,可以实现 AI 计算的加速和部署。AI Infra 主要包括以下内容:AI 训练框架 & 推理引擎;AI 编译 & 计算架构;AI 硬件 & 体系结构。参考资料:;。

AI Infra / LLM / 软件开发 3万+

Bundle Plugin for Maven

FROM: http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html   Simple Example Rather than going straight to a detailed list of plugin features, we will first look at a simple exam...

coffeehot的专栏 2903

WSL2 Ubuntu复现FoundationPose项目(docker)

复现一个基于深度学习的物体姿态估计框架FoundationPose项目,使用docker,WSL2

woaidawangwang的博客 2000

CANN/hixl pre-commit使用指南

[TOC] --- ## 1 Background This guide describes how to use the pre-commit capabilities deployed in the local code repository. These capabilities mainly include code formatting, spell check, and Open

gitblog_00547的博客 494

告别裸机:在FreeRTOS上为STM32移植SOEM 1.4.0的完整指南

本文详细介绍了在FreeRTOS环境下为STM32H7系列芯片移植SOEM 1.4.0的完整指南,涵盖环境准备、任务架构设计、OSAL层适配及网络驱动优化等关键步骤。通过EtherCAT主站解决方案的实现,帮助开发者构建稳定可靠的工业自动化系统,提升实时通信性能。

weixin_33582311的博客 363

电赛备赛笔记:用STM32驱动AD9959信号发生器模块,从接线到出波保姆级教程

本文详细介绍了如何使用STM32驱动AD9959信号发生器模块,从硬件接线到软件调试的全流程。AD9959作为高性能DDS芯片,适用于电子设计竞赛中的信号生成需求。文章包含硬件连接指南、寄存器配置解析、多通道控制技巧以及常见问题解决方案,帮助参赛者快速掌握AD9959的应用。

weixin_31858171的博客 366

深入解析Java ClassNotFoundException:从类加载原理到生产环境实战排查

类加载是Java虚拟机执行引擎的核心机制之一,它负责将类的字节码文件加载到内存中,并转换为可执行的运行时数据结构。其工作原理主要基于双亲委派模型,通过启动类加载器、扩展类加载器和应用类加载器的层级协作,确保核心库的安全性与类定义的唯一性。这一机制的技术价值在于保障了Java平台的稳定性和安全性,同时为模块化、热部署等高级特性提供了基础。在实际的工程实践中,类加载问题常以ClassNotFoundException的形式暴露,尤其在微服务架构和复杂依赖管理中,依赖冲突和类加载器隔离成为高频故障点。例如,在Sp

weixin_34288121的博客 443

自抗扰(ADRC)控制原理及控制器设计

自抗扰控制原理以及控制器设计

weixin_43487974的博客 3万+

工具Cursor(一)介绍&简单使用&特色

下载安装后使用google账户登录。使用代码库索引后:✅ AI 回答更准确,因为它能基于当前项目的索引库回答问题✅ 文件搜索更快✅ AI 能更好地理解跨文件的关系✅ 重构建议更精准实际效果对比使用代码库索引和不使用代码库索引的主要区别:使用代码库索引时,AI 先搜索了项目中的文件,然后根据文件内容回答AI 能准确指出项目中实现的具体功能和代码不使用代码库索引时,AI 只能从一般角度回答,没有针对项目的具体情况什么是 AI 规则?AI 规则是 Cursor 的一个功能。

w_t_y_y的博客 2699

Cursor使用教程:用 Cursor 创建第一个 Java 项目

Cursor是一款基于VS Code的AI编程编辑器,专为开发者设计。安装前需确保JDK 8+、Maven 3.8+等环境配置,支持Windows系统。编辑器提供中文界面选项,可通过扩展市场安装语言包。创建Java项目支持手动和AI提示词两种方式:手动需创建目录结构并编写代码;AI方式则通过自然语言描述快速生成项目框架和代码。标准Java项目包含src/main/java主代码目录、src/test/java测试目录及pom.xml等配置文件。Maven项目中,pom.xml是核心配置文件,管理项目依赖与构

博客 3547

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

IntelliJ IDEA 安装配置与高效使用全攻略:从新手到精通的 Java 开发环境搭建

集成开发环境(IDE)是现代软件开发的基石,它通过集成代码编辑、编译、调试和项目管理等功能,极大提升了开发效率。其核心原理在于提供智能代码补全、实时错误检查和深度框架集成,将开发者从繁琐的配置和重复劳动中解放出来。对于 Java 开发者而言,一个高效、智能的 IDE 是保障工程质量和开发体验的关键。在众多选择中,IntelliJ IDEA 凭借其卓越的代码理解能力和丰富的 **插件生态**,已成为企业级 Java 开发的事实标准。本文聚焦于 **IDEA 安装配置** 这一基础但至关重要的环节,详细解析从版

weixin_30715523的博客 524

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

AWS Java SDK 连接 DigitalOcean Spaces 的 SigV2 兼容方案

对象存储 API 兼容性是云服务集成中的基础技术概念,其核心在于 REST 协议、认证签名与请求构造的精确匹配。DigitalOcean Spaces 声称兼容 Amazon S3 API,但实际仅支持子集功能与 Signature Version 2(SigV2)签名机制,而 AWS Java SDK 默认启用 SigV4 并自动推断 region,导致 InvalidAccessKeyId、NoSuchBucket 等典型异常。该技术方案通过强制 path-style 访问、显式指定 us-east-1

weixin_34228387的博客 503

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

Gitlab+Jenkins+Docker+Harbor+K8s集群搭建CICD平台

Gitlab+Jenkins+Docker+Harbor+K8s集群搭建CICD平台

FamineFree的博客 6089

常用 doc bat 命令总结

常用doc命令总结

sun0322 1万+
上一篇: maven打包的技巧
下一篇: How to exclude jars generated by maven war plugin
DViewer
博客等级 码龄16年 16粉丝 6原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值