当前位置: 首页 > news >正文

普通Java工程可执行JAR两种打包方式探讨

文章目录

  • 一、需求概述
  • 二、代码结构
  • 三、运行结果
  • 四、打包设置
    • 1. 一体化可执行包
    • 2. 带外部依赖lib的可执行包
  • 五、打包运行
    • 1. 源码放送
    • 2. 打包执行
    • 3. 打包结果

一、需求概述

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

打包方式分为2种:

  1. 一体化可执行包
  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*/@Deprecatedpublic 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. 打包结果

在这里插入图片描述


有任何问题和建议,都可以向我提问讨论,大家一起进步,谢谢!

-over-

http://www.lryc.cn/news/331363.html

相关文章:

  • 开源博客项目Blog .NET Core源码学习(13:App.Hosting项目结构分析-1)
  • Vue的双向绑定v-model详细介绍
  • AWS入门实践-S3对象存储的基本用法
  • el-tree-v2渲染树形大数据并设置默认展开
  • 损失函数篇 | YOLOv8更换损失函数之MPDIoU(23年7月首发论文)
  • 【力扣】200.岛屿数量(染色法DFS深搜)
  • 达梦配置ODBC连接
  • 独孤思维:高客单价项目,必须来一个
  • 学习java第三十二天
  • 力扣150. 逆波兰表达式求值
  • hololens 2 投屏 报错
  • 初次在 GitHub 建立仓库以及公开代码的流程 - 公开代码
  • 论文笔记 - :MonoLSS: Learnable Sample Selection For Monocular 3D Detection
  • LVS、HAProxy
  • 开发环境->生产环境
  • 基于AI智能识别技术的智慧展览馆视频监管方案设计
  • Leetcode-894-所有可能的真二叉树-c++
  • Django DRF视图
  • SQLite全文搜索引擎:实现原理、应用实践和版本差异
  • day17-二叉树part04
  • 书生浦语第一次课
  • UE小:UE5.3无法创建C++工程
  • FFmpeg获取视频详情
  • find: paths must precede expression
  • RabbitMQ3.x之九_Docker中安装RabbitMQ
  • vue快速入门(四)v-html
  • 第19次修改了可删除可持久保存的前端html备忘录:换了一个特别的倒计时时钟
  • C++ 2024-4-1 作业
  • 【滑动窗口】Leetcode 串联所有单词的子串
  • golang channel实践代码及注意事项