Java工程中可执行JAR两种打包方式详解

 更新时间:2024年04月03日 11:23:50   作者:爱码少年  
这篇文章主要为大家详细介绍了Java工程中可执行JAR两种打包方式,一体化可执行包和带外部依赖lib的可执行包,有需要的小伙伴可以学习一下

一、需求概述

普通Java工程 docker-show 实现了定时打印docker应用信息,现在需要将其打包成可执行Jar部署到服务器端运行。

打包方式分为2种:

  • 一体化可执行包
  • 带外部依赖lib的可执行包

二、代码结构

三、运行结果

此项目使用了线程池定时打印docker应用名,端口信息

四、打包设置

1. 一体化可执行包

pom文件中引入 maven-assembly-plugin插件,核心配置

			<!-- 方式一:带dependencies运行包 -->
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>3.5.0</version>
				<configuration>
					<appendAssemblyId>false</appendAssemblyId>
					<archive>
						<manifest>
							<mainClass>com.fly.simple.MainRun</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<!--将所有外部依赖JAR都加入生成的JAR包-->
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>
				<executions>
					<execution><!-- 配置执行器 -->
						<id>make-assembly</id>
						<phase>package</phase><!-- 绑定到package阶段 -->
						<goals>
							<goal>single</goal><!-- 只运行一次 -->
						</goals>
					</execution>
				</executions>
			</plugin>

2. 带外部依赖lib的可执行包

pom文件中引入 maven-dependency-plugin、maven-jar-plugin插件,核心配置

			<!-- 方式二:外部依赖lib目录运行包 -->
			<!-- 将项目依赖包复制到<outputDirectory>指定的目录下 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>3.1.2</version>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
							<excludeArtifactIds>lombok</excludeArtifactIds>
							<includeScope>runtime</includeScope>
							<!-- 默认为test,包含所有依赖 -->
						</configuration>
					</execution>
				</executions>
			</plugin>

			<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.fly.simple.MainRun</mainClass>
						</manifest>
						<manifestEntries>
							<Class-Path>./</Class-Path>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>

五、打包运行

1. 源码放送

https://gitcode.com/00fly/demo

git clone https://gitcode.com/00fly/demo.git

或者使用下面的备份文件恢复成原始的项目代码

如何恢复,请移步查阅:神奇代码恢复工具

//goto pom-deps.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.fly</groupId>
	<artifactId>docker-show</artifactId>
	<version>0.0.1</version>
	<name>java-depend</name>
	<url>http://maven.apache.org</url>
	<packaging>jar</packaging>

	<properties>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<version>2.12.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.5</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.12</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>

			<!-- 方式一:带dependencies运行包 -->
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>3.5.0</version>
				<configuration>
					<appendAssemblyId>false</appendAssemblyId>
					<archive>
						<manifest>
							<mainClass>com.fly.simple.MainRun</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<!--将所有外部依赖JAR都加入生成的JAR包-->
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>
				<executions>
					<execution><!-- 配置执行器 -->
						<id>make-assembly</id>
						<phase>package</phase><!-- 绑定到package阶段 -->
						<goals>
							<goal>single</goal><!-- 只运行一次 -->
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>
//goto pom-lib.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.fly</groupId>
	<artifactId>docker-show</artifactId>
	<version>0.0.1</version>
	<name>java-depend</name>
	<url>http://maven.apache.org</url>
	<packaging>jar</packaging>

	<properties>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<version>2.12.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.5</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.12</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			
			<!-- 方式二:外部依赖lib目录运行包 -->
			<!-- 将项目依赖包复制到<outputDirectory>指定的目录下 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>3.1.2</version>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
							<excludeArtifactIds>lombok</excludeArtifactIds>
							<includeScope>runtime</includeScope>
							<!-- 默认为test,包含所有依赖 -->
						</configuration>
					</execution>
				</executions>
			</plugin>

			<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.fly.simple.MainRun</mainClass>
						</manifest>
						<manifestEntries>
							<Class-Path>./</Class-Path>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
//goto pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.fly</groupId>
	<artifactId>docker-show</artifactId>
	<version>0.0.1</version>
	<name>java-depend</name>
	<url>http://maven.apache.org</url>
	<packaging>jar</packaging>

	<properties>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<version>2.12.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.5</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.12</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>

			<!-- 方式一:带dependencies运行包 -->
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>3.5.0</version>
				<configuration>
					<appendAssemblyId>true</appendAssemblyId>
					<archive>
						<manifest>
							<mainClass>com.fly.simple.MainRun</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<!--将所有外部依赖JAR都加入生成的JAR包-->
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>
				<executions>
					<execution><!-- 配置执行器 -->
						<id>make-assembly</id>
						<phase>package</phase><!-- 绑定到package阶段 -->
						<goals>
							<goal>single</goal><!-- 只运行一次 -->
						</goals>
					</execution>
				</executions>
			</plugin>


			<!-- 方式二:外部依赖lib目录运行包 -->
			<!-- 将项目依赖包复制到<outputDirectory>指定的目录下 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>3.1.2</version>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
							<excludeArtifactIds>lombok</excludeArtifactIds>
							<includeScope>runtime</includeScope>
							<!-- 默认为test,包含所有依赖 -->
						</configuration>
					</execution>
				</executions>
			</plugin>

			<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.fly.simple.MainRun</mainClass>
						</manifest>
						<manifestEntries>
							<Class-Path>./</Class-Path>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
//goto src\main\java\com\fly\simple\Executor.java
package com.fly.simple;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Executor
{
    private static String DOCKER_PS_CMD = "docker ps --format \"{{.Names}} {{.Ports}}\"";
    
    /**
     * execute命令
     * 
     * @param command
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public static List<String> execute(String command)
        throws IOException
    {
        List<String> resultList = new ArrayList<>();
        String[] cmd = SystemUtils.IS_OS_WINDOWS ? new String[] {"cmd", "/c", command} : new String[] {"/bin/sh", "-c", command};
        Process ps = Runtime.getRuntime().exec(cmd);
        try (InputStream in = ps.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)))
        {
            String line;
            while ((line = br.readLine()) != null)
            {
                resultList.add(line);
            }
        }
        return resultList;
    }
    
    /**
     * 获取docker相关信息
     * 
     * @throws IOException
     */
    @Deprecated
    public static void printPorts1()
        throws IOException
    {
        Map<String, Set<String>> map = new TreeMap<>();
        for (String line : execute(DOCKER_PS_CMD))
        {
            log.info("{}", line);
            String name = StringUtils.substringBefore(line, " ");
            Set<String> ports =
                Stream.of(StringUtils.substringAfter(line, " ").split(",")).map(p -> StringUtils.substringBetween(p, ":", "->")).filter(StringUtils::isNotBlank).map(p -> p.replace(":", "")).sorted().collect(Collectors.toSet());
            map.put(name, ports);
        }
        log.info("######## {}", map);
    }
    
    /**
     * 获取docker相关信息
     * 
     * @throws IOException
     */
    public static void printPorts()
        throws IOException
    {
        Map<String, Set<String>> map = new TreeMap<>();
        execute(DOCKER_PS_CMD).stream()
            .map(line -> Collections.singletonMap(StringUtils.substringBefore(line, " "),
                Stream.of(StringUtils.substringAfter(line, " ").split(",")).map(p -> StringUtils.substringBetween(p, ":", "->")).filter(StringUtils::isNotBlank).map(p -> p.replace(":", "")).sorted().collect(Collectors.toSet())))
            .forEach(it -> map.putAll(it));
        log.info("######## {}", map);
    }
}
//goto src\main\java\com\fly\simple\MainRun.java
package com.fly.simple;

import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MainRun
{
    /**
     * 线程池保证程序一直运行
     * 
     * @param args
     */
    public static void main(String[] args)
    {
        ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1);
        service.scheduleAtFixedRate(() -> {
            try
            {
                Executor.printPorts();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }, 2, 10, TimeUnit.SECONDS);
    }
}
//goto src\main\resources\log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="off" monitorInterval="0">
	<appenders>
		<console name="Console" target="system_out">
			<patternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		</console>
	</appenders>
	<loggers>
		<root level="INFO">
			<appender-ref ref="Console" />
		</root>
	</loggers>
</configuration>

2. 打包执行

#完整打包
mvn clean package

#一体化可执行包
mvn clean package -f pom-deps.xml

#带外部依赖lib的可执行包
mvn clean package -f pom-lib.xml

3. 打包结果

到此这篇关于Java工程中可执行JAR两种打包方式详解的文章就介绍到这了,更多相关Java打包可执行JAR内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • shiro 认证流程操作

    shiro 认证流程操作

    这篇文章主要介绍了shiro 认证操作的相关资料,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2024-01-01
  • SpringMVC中参数绑定问题实例详解

    SpringMVC中参数绑定问题实例详解

    springmvc是用来处理页面的一些请求,然后将数据再通过视图返回给用户的,下面这篇文章主要给大家介绍了关于SpringMVC中参数绑定问题的相关资料,需要的朋友可以参考下
    2022-04-04
  • Springboot + Mysql8实现读写分离功能

    Springboot + Mysql8实现读写分离功能

    这篇文章主要介绍了Springboot + Mysql8实现读写分离功能,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-10-10
  • 使用ANT与YUI压缩js的实现方法

    使用ANT与YUI压缩js的实现方法

    本篇文章是对使用ANT与YUI压缩js的实现方法进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • SpringBoot中@EnableAutoConfiguration注解源码分析

    SpringBoot中@EnableAutoConfiguration注解源码分析

    这篇文章主要介绍了SpringBoot中@EnableAutoConfiguration注解源码分析,@EnableAutoConfiguration,主要是用于加载Starter目录包之外的、需要Spring自动生成Bean对象的、带有@Configuration注解的类,需要的朋友可以参考下
    2023-08-08
  • Java中数据库加密的方式分享

    Java中数据库加密的方式分享

    在现今互联网时代,数据安全已经成为了我们必须要面对的重要课题,在本文中,我们将会介绍Java中常用的几种数据库加密方式并分析一下它们的优缺点,希望对大家有所帮助
    2023-05-05
  • Java switch关键字原理及用法详解

    Java switch关键字原理及用法详解

    这篇文章主要介绍了Java中 switch关键原理及用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • Netty实现自定义协议编解码器

    Netty实现自定义协议编解码器

    这篇文章主要为大家介绍了Netty实现自定义协议编解码器示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • Spring Boot 整合 Fisco Bcos部署、调用区块链合约的案例

    Spring Boot 整合 Fisco Bcos部署、调用区块链合约的案例

    本篇文章介绍 Spring Boot 整合 Fisco Bcos 的相关技术,最最重要的技术点,部署、调用区块链合约的工程案例,本文通过流程分析给大家介绍的非常详细,需要的朋友参考下吧
    2022-01-01
  • JAVA验证码工具实例代码

    JAVA验证码工具实例代码

    这篇文章主要介绍了JAVA验证码工具实例代码,需要的朋友可以参考下
    2018-03-03

最新评论