Maven项目打包成jar包运行(将第三方引用包与项目代码打包成一个jar包)
一、新建Maven项目,Packaging为jar
二、新建主类
主类代码如下:
package com.example.demo;
import javax.swing.JFrame;
public class GuiMain extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
GuiMain gm = new GuiMain();
gm.setTitle("JFrame窗口");
gm.setSize(640, 480);
gm.setResizable(false);
gm.setLocationRelativeTo(null);
gm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gm.setVisible(true);
}
}
三、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>DemoGui</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<project.build.sourceVersion>1.8</project.build.sourceVersion>
<project.build.targetVersion>1.8</project.build.targetVersion>
</properties>
<dependencies>
<!-- JSON -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.57</version>
</dependency>
</dependencies>
<build>
<finalName>DemoGui</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${project.build.sourceVersion}</source>
<target>${project.build.targetVersion}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<!-- 打包时跳过单元测试 -->
<skipTests>true</skipTests>
</configuration>
</plugin>
<!-- 打包指令mvn clean package -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>*.*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.example.demo.GuiMain</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
四、清理、编译、打包
项目结构最终如下:
打开命令提示符,cd到该项目的根目录下,即与pom.xml同一目录,然后运行mvn clean compile package,效果如图所示:
进入项目中的target目录,文件列表如图所示:
五、运行
将DemoGui.jar拷贝至指定位置,如E:\release\java下,如图所示 :
通过命令提示符运行java -jar DemoGui.jar,即可将程序运行。
或者
新建一个批处理文件run.bat,将该指令写在批处理文件中,以后双击运行该批处理文件,即可将程序运行。
运行后效果如图所示:
通过run.bat运行会自带一个控制台输出,如果不想要,修改运行指令为start javaw -jar DemoGui.jar即可。