SpringBootServletInitializer 教程展示了如何从传统的 WAR 部署中部署 Spring Boot 应用。
当前的趋势是从可执行的 JAR 部署 Spring Boot 应用。
Spring 是流行的 Java 应用框架。 Spring Boot 致力于以最小的努力创建独立的,基于生产级别的基于 Spring 的应用。
SpringBootServletInitializer
SpringBootServletInitializer是从传统 WAR 部署运行 SpringApplication 的接口。 它将 Servlet,Filter 和 ServletContextInitializer Bean 从应用上下文绑定到服务器。
SpringBootServletInitializer 示例
该应用创建一个简单的 Spring Boot RESTful 应用并将其打包到 WAR 中。
pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ │ Application.java
│ │ └───controller
│ │ MyController.java
│ └───resources
└───test
└───java
这是项目结构。
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.zetcode</groupId>
<artifactId>servletinitializer</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
这是 Maven 构建文件。 spring-boot-starter-web是使用 Spring MVC 构建 Web(包括 RESTful)应用的入门程序。
该应用打包到一个 WAR 文件中。
com/zetcode/controller/MyController.java
package com.zetcode.controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE)
public String index() {
return "Hello there";
}
}
这是 Spring Boot Web 应用的控制器类。 控制器以@Restontroller注解修饰。
@GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE)
public String index() {
return "Hello there";
}
对主页的 GET 请求返回一个字符串。 绑定是通过@GetMapping完成的。
com/zetcode/Application.java
package com.zetcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Application设置 Spring Boot 应用。 它从SpringBootServletInitializer扩展而来,可以将其部署为 WAR。
通过将 WAR 部署在 Tomcat 服务器上并将其作为具有嵌入式 Tomcat 的自可执行 Web 归档执行,可以运行该应用。
在本教程中,我们创建了第一个可从传统 WAR 部署的 Spring Boot Web 应用。
极客教程