java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java打包可执行JAR

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

作者:爱码少年

这篇文章主要为大家详细介绍了Java工程中可执行JAR两种打包方式,一体化可执行包和带外部依赖lib的可执行包,有需要的小伙伴可以学习一下

一、需求概述

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

打包方式分为2种:

二、代码结构

三、运行结果

此项目使用了线程池定时打印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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文