关键词

SpringBoot项目打成war和jar的区别说明

Spring Boot 是一个轻量化的框架,可以用于快速构建基于 Spring 的 Web 应用程序。它们可以以两种不同的形式进行部署:WAR 和 JAR。这里将详细讲解 WAR 和 JAR 的区别,以及其在 Spring Boot 项目中运用的使用方法。

WAR 和 JAR 的区别

WAR 和 JAR 是两个在 Java 环境中经常使用的文件类型。它们有以下区别:

  1. JAR (Java Archive):是一种通用的 Java 应用程序存档文件格式。常用于分发和部署 Java 应用程序。

  2. WAR(Web Application Archive):是一种特定类型的 JAR 文件,用于打包和分发 Web 应用程序。

结论: 简单来说,JAR 是通用的 Java 应用程序文件格式,而 WAR 是专门用于在 Web 应用程序中使用的一种文件格式。

制作 Spring Boot 项目的 WAR 和 JAR 包

下面是制作 Spring Boot 项目的 WAR 包和 JAR 包的具体步骤:

制作 WAR 包

  1. 修改 pom.xml 文件,增加以下依赖:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

2.在 Spring Boot 主类的头部添加以下注解,实现 WAR 包的部署:

    @SpringBootApplication
    public class SpringBootApp extends SpringBootServletInitializer {

        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(SpringBootApp.class);
        }

        public static void main(String[] args) {
            SpringApplication.run(SpringBootApp.class, args);
        }
    }
  1. 执行命令:mvn clean package 打包目标文件。

  2. 生成的 WAR 文件位于 /target 目录下。

制作 JAR 包

  1. 修改 pom.xml 文件,将以下依赖项注释掉:
<!-- <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency> -->
  1. 清除所有 Tomcat 相关依赖项。

  2. 执行命令:mvn clean package 打包目标文件。

  3. 生成的 JAR 文件位于 /target 目录下。

示例

下面给出两个示例,一个是将 Spring Boot 项目打成 WAR 包的实现方法,一个是将 Spring Boot 项目打成 JAR 包的实现方法。

示例 1: 制作 WAR 包

  1. 打开 Spring Boot Maven 实例项目。

  2. 修改 pom.xml 中的依赖项。

  3. 使用以下命令来构建并打包 WAR 文件:

$ mvn clean package
  1. 运行以下命令将 WAR 文件部署到 Tomcat 服务器上:
$ cp target/hello-world-0.0.1-SNAPSHOT.war /path/to/www/webapps/hello-world.war
  1. 启动 Tomcat 服务器。

  2. 在浏览器访问 http://localhost:8080/hello-world 查看页面。

示例 2: 制作 JAR 包

  1. 打开 Spring Boot Maven 实例项目。

  2. 修改 pom.xml,将以下内容注释掉:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
  1. 使用以下命令构建并打包 JAR 文件:
$ mvn clean package
  1. 运行以下命令启动 JAR 文件:
$ java -jar target/hello-world-0.0.1-SNAPSHOT.jar
  1. 在浏览器访问 http://localhost:8080/ 端口以查看 Spring Boot 应用程序运行情况。

总之,在选择部署 Spring Boot 项目时,需要根据自己的需要选择 WAR 包或 JAR 包。如果需要将 Spring Boot 项目部署到 Web 服务器,那么应该选择 WAR 包。如果只是需要部署一个简单的调用控制台或命令行的程序,那么应该选择 JAR 包。

本文链接:http://task.lmcjl.com/news/8037.html

展开阅读全文