ZetCode

Spring WebApplicationInitializer 教程

最后修改于 2023 年 10 月 18 日

Spring WebApplicationInitializer 教程展示了如何使用 WebApplicationInitializer 以编程方式引导 Spring Web 应用程序。

Spring 是一个流行的 Java 应用程序框架,用于创建企业级应用程序。

WebApplicationInitializer

WebApplicationInitializer 用于启动 Spring Web 应用程序。WebApplicationInitializer 注册 Spring DispatcherServlet 并创建一个 Spring Web 应用程序上下文。大多数情况下,开发人员使用 AbstractAnnotationConfigDispatcherServletInitializer,它是 WebApplicationInitializer 的一个实现,来创建 Spring Web 应用程序。

传统上,基于 Servlet 的 Java Web 应用程序使用 web.xml 文件来配置 Java Web 应用程序。自 Servlet 3.0 起,可以通过 Servlet Context Listener 以编程方式创建 Web 应用程序。

Spring WebApplicationInitializer 示例

下面的应用程序使用 WebApplicationInitializer 创建一个 Spring Web 应用程序。

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           ├───config
│   │           │       MyWebInitializer.java
│   │           │       WebConfig.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>mockmvcex</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <spring-version>5.3.23</spring-version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.4.0</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.23</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.2</version>
            </plugin>

        </plugins>
    </build>
</project>

pom.xml 文件中,我们有以下依赖项:logback-classicjavax.servlet-apispring-webmvc

com/zetcode/config/MyWebInitializer.java
package com.zetcode.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

public class MyWebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        var ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebConfig.class);
        ctx.setServletContext(servletContext);

        var servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
}

MyWebInitializer 实现了 WebApplicationInitializer 接口。引导代码在 onStartup 方法中。

var ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ctx.setServletContext(servletContext);

我们创建一个 AnnotationConfigWebApplicationContext,并使用 register 注册一个 Web 配置文件。我们将应用程序上下文绑定到 Servlet 上下文。

var servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");

在这里,我们注册了一个 Spring DispatcherServlet,它是 Spring Web 应用程序的前端控制器。

com/zetcode/config/WebConfig.java
package com.zetcode.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.zetcode")
public class WebConfig {
}

WebConfig 使用 @EnableWebMvc 启用 Spring MVC 注解,并为 com.zetcode 包配置组件扫描。

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 home() {

        return "This is home page";
    }
}

MyController 是一个 RESTful 控制器,它有一个映射。

$ curl localhost:8080
This is home page

我们使用 curl 工具连接到主页。

在本篇文章中,我们使用 WebApplicationInitializer 创建了一个简单的 Spring Web 应用程序。

作者

我叫 Jan Bodnar,是一名充满激情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在教学编程方面拥有十多年的经验。

列出 所有 Spring 教程