JavaSE 打包

在Java开发中,打包是非常重要的一个环节,它将源代码、依赖库、配置文件等资源整合成一个可执行的文件或者库。本文将介绍JavaSE中的打包方式,包括JAR、WAR和JAR-with-dependencies。

JAR

JAR(Java Archive)是Java平台标准的压缩文件格式,可以用来存储多个Java类文件、资源文件和元数据文件。通过JAR文件,我们可以方便地将应用程序打包成可执行的独立文件。下面是一个简单的示例,演示如何使用命令行将多个.class文件打包成JAR文件:

// HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
$ javac HelloWorld.java
$ jar cvf HelloWorld.jar HelloWorld.class

以上命令将编译后的HelloWorld.class文件打包成名为HelloWorld.jar的JAR文件。我们可以通过java -jar HelloWorld.jar命令执行这个JAR文件。

WAR

WAR(Web Archive)是一种用于打包Web应用程序的文件格式,通常用于部署到Java Web服务器上。WAR文件包含了Web应用程序的所有文件,包括HTML、JSP、Servlet、类文件、配置文件等。下面是一个简单的示例,演示如何将一个简单的Web应用程序打包成WAR文件:

// index.jsp
<html>
<head>
    <title>Hello, World!</title>
</head>
<body>
    Hello, World!
</body>
</html>
<!-- WEB-INF/web.xml -->
<web-app>
    <display-name>HelloWorld</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
$ jar cvf HelloWorld.war index.jsp WEB-INF/web.xml

以上命令将index.jsp和WEB-INF目录下的web.xml文件打包成名为HelloWorld.war的WAR文件。我们可以将这个WAR文件部署到Java Web服务器上。

JAR-with-dependencies

有时候我们的应用程序依赖于一些第三方库,为了方便部署,我们可以将这些依赖库一起打包到JAR文件中。Maven是一个常用的构建工具,可以帮助我们实现JAR-with-dependencies的打包。下面是一个简单的示例,演示如何使用Maven将一个带有依赖库的Java应用程序打包成可执行的JAR文件:

<!-- pom.xml -->
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>HelloWorld</artifactId>
    <version>1.0</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.1.1</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

通过上述pom.xml配置文件,我们可以使用mvn package命令将带有依赖库的Java应用程序打包成名为HelloWorld-1.0-jar-with-dependencies.jar的JAR文件。这个JAR文件包含了项目的类文件以及所有依赖库。

关系图

下面是一个简单的关系图,演示了JAR、WAR和JAR-with-dependencies之间的关系:

erDiagram
    JAR --|> JAR-with-dependencies: extends
    WAR --|> JAR: extends

流程图

最后,我们来看一下JavaSE打包的整体流程:

flowchart TD
    A(编写Java代码) --> B(编译Java