Running a Spring Boot App with Maven vs an Executable War/Jar – 用Maven和可执行的War/Jar运行Spring Boot应用程序

最后修改: 2019年 8月 6日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this tutorial, we’ll explore the differences between starting a Spring Boot web application via the mvn spring-boot:run command and running it after it’s compiled into a jar/war package via the java -jar command.

在本教程中,我们将探讨通过mvn spring-boot:run命令启动Spring Boot网络应用程序与通过java -jar命令将其编译成jar/war包后运行之间的区别。

For the purpose of this tutorial, we’ll assume familiarity with the configuration of the Spring Boot repackage goal. For more details on this topic, please read Create a Fat Jar App with Spring Boot.

在本教程中,我们将假设对Spring Boot repackage目标的配置非常熟悉。有关该主题的详细信息,请阅读用Spring Boot创建Fat Jar应用程序

2. The Spring Boot Maven Plugin

2.Spring Boot Maven Plugin

When writing a Spring Boot application, the Spring Boot Maven plugin is the recommended tool to build, test, and package our code.

在编写Spring Boot应用程序时,Spring Boot Maven插件是用于构建、测试和打包我们代码的推荐工具。

This plugin ships with lots of convenient features, such as:

这个插件有很多方便的功能,如:。

  • it resolves the correct dependency versions for us
  • it can package all our dependencies (including an embedded application server if needed) in a single, runnable fat jar/war, and will also:
    • manage the classpath configuration for us, so we can skip that long -cp option in our java -jar command
    • implement a custom ClassLoader to locate and load all the external jar libraries now nested inside the package
    • automatically find the main() method and configure it in the manifest, so we don’t have to specify the main class in our java -jar command

3. Running the Code With Maven in Exploded Form

3.用Maven运行代码的解析形式

When we’re working on a web application, we can leverage another very interesting feature of the Spring Boot Maven plugin: the ability to automatically deploy our web application in an embedded application server.

当我们在开发网络应用时,我们可以利用Spring Boot Maven插件的另一个非常有趣的功能:在嵌入式应用服务器中自动部署网络应用的能力。

We only need one dependency to let the plugin know we want to use Tomcat to run our code:

我们只需要一个依赖关系,让插件知道我们想用Tomcat来运行我们的代码。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId> 
</dependency>

Now when executing the mvn spring-boot:run command in our project root folder, the plugin reads the pom configuration and understands that we require a web application container.

现在,当在我们的项目根目录下执行mvn spring-boot:run命令时,该插件会读取pom配置并理解我们需要一个Web应用容器。

Executing the mvn spring-boot:run command triggers the download of Apache Tomcat and initializes the startup of Tomcat:

执行mvn spring-boot:run命令会触发Apache Tomcat的下载并初始化Tomcat的启动:

$ mvn spring-boot:run
...
...
[INFO] --------------------< com.baeldung:spring-boot-ops >--------------------
[INFO] Building spring-boot-ops 0.0.1-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:2.1.3.RELEASE:run (default-cli) > test-compile @ spring-boot-ops >>>
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/tomcat/embed/tomcat-embed-core/9.0.16/tomcat-embed-core-9.0.16.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/tomcat/embed/tomcat-embed-core/9.0.16/tomcat-embed-core-9.0.16.pom (1.8 kB at 2.8 kB/s)
...
...
[INFO] --- spring-boot-maven-plugin:2.1.3.RELEASE:run (default-cli) @ spring-boot-ops ---
...
...
11:33:36.648 [main] INFO  o.a.catalina.core.StandardService - Starting service [Tomcat]
11:33:36.649 [main] INFO  o.a.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.16]
...
...
11:33:36.952 [main] INFO  o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
...
...
11:33:48.223 [main] INFO  o.a.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8080"]
11:33:48.289 [main] INFO  o.s.b.w.e.tomcat.TomcatWebServer - Tomcat started on port(s): 8080 (http) with context path ''
11:33:48.292 [main] INFO  org.baeldung.boot.Application - Started Application in 22.454 seconds (JVM running for 37.692)

When the log shows the line containing ‘Started Application’, our web application is ready to be queried via the browser at the address http://localhost:8080/

当日志显示包含 “Started Application “一行时,我们的网络应用已经准备好通过浏览器查询,地址是http://localhost:8080/。

4. Running the Code as a Stand-Alone Packaged Application

4.将代码作为独立的打包应用程序运行

Once we pass the development phase and progress toward bringing our application to production, we need to package our application.

一旦我们通过了开发阶段,并逐步将我们的应用程序推向生产,我们就需要对我们的应用程序进行打包。

Unfortunately, if we’re working with a jar package, the basic Maven package goal doesn’t include any of the external dependencies. This means that we can only use it as a library in a bigger project.

不幸的是,如果我们使用的是jar包,Maven的基本package目标并不包括任何外部依赖。这意味着我们只能将其作为更大项目中的一个库。

To circumvent this limitation, we need to leverage the Maven Spring Boot plugin repackage goal to run our jar/war as a stand-alone application.

为了规避这一限制, 我们需要利用Maven Spring Boot插件 repackage目标,将我们的jar/war作为一个独立的应用程序运行。

4.1. Configuration

4.1.配置

Usually, we only need to configure the build plugin:

通常情况下,我们只需要配置构建插件。

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        ...
    </plugins>
</build>

Since our example project contains more than one main class, we have to tell Java which class to run, either by configuring the plugin:

由于我们的例子项目包含不止一个主类,我们必须告诉Java要运行哪个类,可以通过配置插件。

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <configuration>
                <mainClass>com.baeldung.webjar.WebjarsdemoApplication</mainClass>
            </configuration>
        </execution>
    </executions>
</plugin>

or setting the start-class property:

或设置start-class属性。

<properties>
    <start-class>com.baeldung.webjar.WebjarsdemoApplication</start-class>
</properties>

4.2. Running the Application

4.2.运行应用程序

Now we can run our example war with two simple commands:

现在我们可以用两个简单的命令来运行我们的战争实例。

$ mvn clean package spring-boot:repackage
$ java -jar target/spring-boot-ops.war

More details regarding how to run a jar file can be found in our article Run JAR Application With Command Line Arguments.

关于如何运行jar文件的更多细节可以在我们的文章使用命令行参数运行JAR应用程序中找到。

4.3. Inside the War File

4.3.战争文件内部

To better understand how the above mentioned command can run a full server application, we can take a look into our spring-boot-ops.war.

为了更好地理解上述命令如何运行一个完整的服务器应用程序,我们可以看一下我们的spring-boot-ops.war.

If we uncompress it and peek inside, we’ll find the usual suspects:

如果我们把它解压并偷看里面,我们会发现常见的嫌疑人。

  • META-INF, with the auto-generated MANIFEST.MF
  • WEB-INF/classes, containing our compiled classes
  • WEB-INF/lib, which holds our war dependencies and the embedded Tomcat jar files

That’s not all though, as there are some folders specific to our fat package configuration:

这还不是全部,因为有一些文件夹是针对我们的胖子包配置的。

  •  WEB-INF/lib-provided, containing external libraries required when running embedded, but not required when deploying
  • org/springframework/boot/loader, which holds the Spring Boot custom class loader. This library is responsible for loading our external dependencies and making them accessible in runtime.

4.4. Inside the War Manifest

4.4.战争宣言》的内部

As mentioned before, the Maven Spring Boot plugin finds the main class and generates the configuration needed for running the java command.

如前所述,Maven Spring Boot插件找到主类并生成运行java命令所需的配置。

The resulting MANIFEST.MF has some additional lines:

产生的MANIFEST.MF有一些额外的行。

Start-Class: com.baeldung.webjar.WebjarsdemoApplication
Main-Class: org.springframework.boot.loader.WarLauncher

In particular, we can observe that the last one specifies the Spring Boot class loader launcher to use.

特别是,我们可以看到,最后一个指定了要使用的Spring Boot类加载器启动器。

4.5. Inside a Jar File

4.5.Jar文件内部

Due to the default packaging strategy, our war packaging scenario doesn’t differ much, whether we use the Spring Boot Maven Plugin or not.

由于默认的打包策略,无论我们是否使用Spring Boot Maven插件,我们的战打包方案都没有太大区别。

To better appreciate the advantages of the plugin, we can try changing the pom packaging configuration to jar, and running mvn clean package again.

为了更好地体会该插件的优势,我们可以尝试将pompackaging配置改为jar,,并再次运行mvn clean package

We can now observe that our fat jar is organized a bit differently from our previous war file:

我们现在可以观察到,我们的fat jar的组织方式与之前的war文件有些不同。

  • All our classes and resources folders are now located under BOOT-INF/classes.
  • BOOT-INF/lib holds all the external libraries.

Without the plugin, the lib folder wouldn’t exist, and all the content of BOOT-INF/classes would be located in the root of the package.

如果没有这个插件,lib文件夹就不会存在,而BOOT-INF/classes的所有内容都将位于软件包的根部。

4.6. Inside the Jar Manifest

4.6.罐子清单内部

The MANIFEST.MF has also changed, featuring these additional lines:

MANIFEST.MF也发生了变化,增加了这些行。

Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Spring-Boot-Version: 2.1.3.RELEASE
Main-Class: org.springframework.boot.loader.JarLauncher

Spring-Boot-Classes and Spring-Boot-Lib are particularly interesting, as they tell us where the class loader is going to find classes and external libraries.

Spring-Boot-ClassesSpring-Boot-Lib特别有趣,因为它们告诉我们类加载器将在哪里找到类和外部库。

5. How to Choose

5.如何选择

When analyzing tools, it’s imperative we take into account the purpose these tools were created for. Do we want to ease the development, or ensure smooth deployment and portability? Let’s have a look at the phases most affected by this choice.

在分析工具时,我们必须考虑到这些工具的创建目的。我们是想缓解开发,还是确保顺利部署和可移植性?让我们来看看受这种选择影响最大的阶段。

5.1. Development

5.1.发展

As developers, we often spend most of our time coding without needing to spend a lot of time setting up our environment to run the code locally. In simple applications, that’s usually not a concern. But for more complex projects, we may need to set environment variables, start servers, and populate databases.

作为开发者,我们常常把大部分时间花在编码上,而不需要花很多时间来设置环境以在本地运行代码。在简单的应用程序中,这通常不是一个问题。但对于更复杂的项目,我们可能需要设置环境变量,启动服务器,并填充数据库。

Configuring the right environment every time we want to run the application would be very impractical, especially if more than one service has to run at the same time.

每次我们想运行应用程序时,配置正确的环境将是非常不切实际的,特别是如果有多个服务必须同时运行。

That’s where running the code with Maven helps us. We already have the entire codebase checked out locally, so we can leverage the pom configuration and resource files. We can set environment variables, spawn an in-memory database, and even download the correct server version and deploy our application with one command.

这就是用Maven运行代码的好处。我们已经在本地检查了整个代码库,所以我们可以利用pom配置和资源文件。我们可以设置环境变量,生成内存数据库,甚至下载正确的服务器版本,用一个命令部署我们的应用程序。

Even in a multi-module codebase, where each module needs different variables and server versions, we can easily run the right environment via Maven profiles.

即使在多模块代码库中,每个模块都需要不同的变量和服务器版本,我们也可以通过Maven配置文件轻松运行正确的环境。

5.2. Production

5.2.生产

The more we move toward production, the more the conversation shifts to stability and security. That’s why we can’t apply the process used for our development machine to a server with live customers.

我们越是走向生产,对话就越是转移到稳定性和安全性。这就是为什么我们不能把用于开发机器的过程应用于有活客户的服务器。

Running the code through Maven at this stage is bad practice for multiple reasons:

在这个阶段通过Maven运行代码是不好的做法,原因有很多:

  • First of all, we would need to install Maven.
  • Then, just because we need to compile the code, we need the full Java Development Kit (JDK).
  • Next, we have to copy the codebase to our server, leaving all our proprietary code in plain text.
  • The mvn command has to execute all phases of the life cycle (find sources, compile, and run).
  • Thanks to the previous point, we’d also waste CPU, and in the case of a cloud server, money.
  • Maven spawns multiple Java processes, each using memory (by default, they each use the same memory amount as the parent process).
  • Finally, if we have multiple servers to deploy, all of the above is repeated on each one.

These are just a few reasons why shipping the application as a package is more practical for production.

这些只是几个原因,为什么将应用程序作为一个包来运输对生产来说更实用

6. Conclusion

6.结语

In this article, we explored the differences between running our code via Maven and via the java -jar command. We also went through a quick overview of some practical case scenarios.

在这篇文章中,我们探讨了通过Maven和通过java -jar命令运行代码的区别。我们还快速浏览了一些实际案例场景。

The source code used in this article is available over on GitHub.

本文所使用的源代码可在GitHub上找到