使用Maven Assembly Plugin打包Java+MySQL项目为可执行JAR

下面我将详细介绍如何使用Maven Assembly Plugin将Java Swing + MySQL项目打包成可执行JAR文件。

完整的项目结构和配置

1. 项目目录结构

inventory-management-system/
├── src/
│   └── main/
│       ├── java/
│       │   └── com/
│       │       └── inventory/
│       │           ├── Main.java
│       │           ├── LoginFrame.java
│       │           ├── InventoryManagementSystem.java
│       │           └── dao/
│       │               ├── DatabaseConnection.java
│       │               ├── ProductDAO.java
│       │               └── ...
│       ├── resources/
│       │   ├── db/
│       │   │   └── schema.sql
│       │   ├── icons/
│       │   └── config.properties
│       └── assembly/
│           └── package.xml
├── target/
├── pom.xml
└── README.md

2. 完整的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.inventory</groupId>
    <artifactId>inventory-management-system</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
    
    <name>商品库存管理系统</name>
    <description>基于Java Swing和MySQL的商品库存管理系统</description>
    
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <mysql.version>8.0.33</mysql.version>
        <maven-assembly-plugin.version>3.6.0</maven-assembly-plugin.version>
    </properties>
    
    <dependencies>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        
        <!-- 日志框架 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.4.11</version>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <!-- 编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.11.0</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            
            <!-- Assembly Plugin 配置 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>${maven-assembly-plugin.version}</version>
                <configuration>
                    <!-- 指定描述文件 -->
                    <descriptors>
                        <descriptor>src/main/assembly/package.xml</descriptor>
                    </descriptors>
                    <archive>
                        <manifest>
                            <!-- 指定主类 -->
                            <mainClass>com.inventory.Main</mainClass>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>.</Class-Path>
                        </manifestEntries>
                    </archive>
                    <!-- 最终生成的JAR文件名 -->
                    <finalName>inventory-system-${version}</finalName>
                    <appendAssemblyId>false</appendAssemblyId>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            
            <!-- 资源文件处理 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.3.1</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
        
        <!-- 资源文件配置 -->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.sql</include>
                    <include>**/*.xml</include>
                    <include>**/*.png</include>
                    <include>**/*.jpg</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

3. Assembly描述文件 (src/main/assembly/package.xml)

<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.1.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.1.0 
          http://maven.apache.org/xsd/assembly-2.1.0.xsd">
    <id>full</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    
    <!-- 包含依赖的JAR -->
    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <useProjectArtifact>true</useProjectArtifact>
            <unpack>true</unpack>
            <scope>runtime</scope>
            <!-- 排除不需要的依赖 -->
            <excludes>
                <exclude>junit:junit</exclude>
            </excludes>
        </dependencySet>
    </dependencySets>
    
    <!-- 包含项目文件 -->
    <fileSets>
        <!-- 包含编译后的class文件 -->
        <fileSet>
            <directory>${project.build.outputDirectory}</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>**/*</include>
            </includes>
        </fileSet>
        
        <!-- 包含资源文件 -->
        <fileSet>
            <directory>src/main/resources</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>**/*</include>
            </includes>
        </fileSet>
        
        <!-- 包含启动脚本 -->
        <fileSet>
            <directory>src/main/scripts</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>*.sh</include>
                <include>*.bat</include>
            </includes>
            <fileMode>0755</fileMode>
        </fileSet>
    </fileSets>
</assembly>

4. 主类代码示例

package com.inventory;

import com.inventory.dao.DatabaseConnection;
import javax.swing.*;
import java.awt.*;
import java.io.InputStream;
import java.util.Properties;

public class Main {
    public static void main(String[] args) {
        // 设置系统外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // 初始化数据库连接
        initializeDatabase();
        
        // 启动GUI
        SwingUtilities.invokeLater(() -> {
            new LoginFrame().setVisible(true);
        });
    }
    
    private static void initializeDatabase() {
        try {
            // 从配置文件加载数据库配置
            Properties props = new Properties();
            InputStream is = Main.class.getClassLoader().getResourceAsStream("config.properties");
            if (is != null) {
                props.load(is);
                
                String dbUrl = props.getProperty("db.url", "jdbc:mysql://localhost:3306/inventory_db");
                String dbUser = props.getProperty("db.user", "root");
                String dbPassword = props.getProperty("db.password", "password");
                
                DatabaseConnection.initialize(dbUrl, dbUser, dbPassword);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, 
                "数据库初始化失败: " + e.getMessage(), 
                "错误", 
                JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
    }
}

5. 数据库连接类

package com.inventory.dao;

import java.sql.*;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DatabaseConnection {
    private static Connection connection;
    private static String dbUrl;
    private static String dbUser;
    private static String dbPassword;
    
    public static void initialize(String url, String user, String password) {
        dbUrl = url;
        dbUser = user;
        dbPassword = password;
        createDatabaseIfNotExists();
    }
    
    public static Connection getConnection() throws SQLException {
        if (connection == null || connection.isClosed()) {
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
            } catch (ClassNotFoundException e) {
                throw new SQLException("MySQL JDBC Driver not found", e);
            }
        }
        return connection;
    }
    
    private static void createDatabaseIfNotExists() {
        try {
            // 提取数据库名称
            String dbName = extractDatabaseName(dbUrl);
            String baseUrl = dbUrl.substring(0, dbUrl.lastIndexOf("/"));
            
            // 连接到MySQL(不指定数据库)
            Connection tempConn = DriverManager.getConnection(baseUrl, dbUser, dbPassword);
            Statement stmt = tempConn.createStatement();
            
            // 创建数据库(如果不存在)
            stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + dbName);
            
            stmt.close();
            tempConn.close();
            
            // 执行建表脚本
            executeSchemaScript();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static String extractDatabaseName(String url) {
        int lastSlash = url.lastIndexOf("/");
        int questionMark = url.indexOf("?", lastSlash);
        if (questionMark == -1) {
            return url.substring(lastSlash + 1);
        }
        return url.substring(lastSlash + 1, questionMark);
    }
    
    private static void executeSchemaScript() {
        try (InputStream is = DatabaseConnection.class.getClassLoader()
                .getResourceAsStream("db/schema.sql")) {
            if (is != null) {
                String schema = new String(is.readAllBytes());
                String[] statements = schema.split(";");
                
                Connection conn = getConnection();
                Statement stmt = conn.createStatement();
                
                for (String statement : statements) {
                    String trimmed = statement.trim();
                    if (!trimmed.isEmpty()) {
                        stmt.execute(trimmed);
                    }
                }
                
                stmt.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

6. 配置文件 (src/main/resources/config.properties)

# 数据库配置
db.url=jdbc:mysql://localhost:3306/inventory_db
db.user=root
db.password=password

# 应用配置
app.name=商品库存管理系统
app.version=1.0.0

# 日志配置
logging.level=INFO

7. 数据库建表脚本 (src/main/resources/db/schema.sql)

CREATE DATABASE IF NOT EXISTS inventory_db;
USE inventory_db;

CREATE TABLE IF NOT EXISTS suppliers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    contact VARCHAR(50),
    phone VARCHAR(20),
    address VARCHAR(200),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    category VARCHAR(50),
    price DECIMAL(10,2),
    supplier_id INT,
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (supplier_id) REFERENCES suppliers(id)
);

CREATE TABLE IF NOT EXISTS inventory (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_id INT,
    quantity INT,
    last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (product_id) REFERENCES products(id)
);

8. 打包和运行命令

# 清理并打包项目
mvn clean compile assembly:single

# 运行JAR文件
java -jar target/inventory-system-1.0.0.jar

# 或者指定数据库参数运行
java -jar target/inventory-system-1.0.0.jar --db.url=jdbc:mysql://localhost:3306/inventory_db --db.user=root --db.password=123456

9. 启动脚本示例 (src/main/scripts/start.bat)

@echo off
title 商品库存管理系统
echo 启动商品库存管理系统...
java -jar inventory-system-1.0.0.jar
pause

10. 高级打包配置(可选)- 创建包含依赖的独立JAR

如果想要创建包含所有依赖的fat JAR,可以使用以下替代的assembly配置:

<!-- 在pom.xml中添加 -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.5.0</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>com.inventory.Main</mainClass>
                    </transformer>
                </transformers>
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/*.SF</exclude>
                            <exclude>META-INF/*.DSA</exclude>
                            <exclude>META-INF/*.RSA</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
        </execution>
    </executions>
</plugin>

打包流程总结

  1. 配置pom.xml:添加Maven Assembly Plugin配置

  2. 创建assembly描述文件:定义打包规则

  3. 组织项目结构:确保资源文件正确放置

  4. 执行打包命令mvn clean compile assembly:single

  5. 测试运行:验证生成的JAR文件

常见问题解决

  1. 依赖冲突:使用mvn dependency:tree检查依赖关系

  2. 资源文件找不到:确保资源文件在src/main/resources目录

  3. 主类找不到:检查pom.xml中的mainClass配置

  4. 数据库驱动问题:确保MySQL驱动版本兼容

这样配置后,你就可以通过一条命令mvn clean compile assembly:single轻松打包整个项目为可执行的JAR文件了!

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐