使用 Spring 快速创建 web 应用的两种方式

介绍

本篇文章主要介绍,如何使用 Spring 开发一个 Web 应用。
我们将研究用 Spring Boot 开发一个 web 应用,并研究用非 Spring Boot 的方法。
我们将主要使用 Java 配置,但还要了解它们的等效的 XML 配置。

使用 Spring Boot

Maven 依赖

首先,我们需要引用 spring-boot-starter-web 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>
复制代码

该依赖包含:

  • Spring Web 应用程序所需的 spring-webspring-webmvc 模块
  • Tomcat 容器,这样我们就可以直接运行 Web 应用程序,而无需安装 Tomcat

创建一个Spring Boot 应用程序

使用 Spring Boot 的最直接的方法是创建一个主类,并添加 @SpringBootApplication 注解:

@SpringBootApplication
public class SpringBootRestApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootRestApplication.class, args);
    }
}
复制代码

此单个注释等效于使用 @Configuration@EnableAutoConfiguration@ComponentScan
默认情况下,它将扫描本包和它的子包中的所有组件。
接下来,对于基于 Java 的 Spring Bean 配置,我们需要创建一个配置类,并使用 @Configuration 注解:

@Configuration
public class WebConfig {
 
}
复制代码

该注解是 Spring 主要使用的配置。 它本身使用 @Component 进行元注解,这使注解的类成为标准 bean,因此也成为组件扫描时的候选对象。
让我们看看使用核心 spring-webmvc 库的方法。

使用 spring-webmvc

Maven 依赖

首先,我们需要引用 spring-webmvc 依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
复制代码

基于 java 的 Web 配置

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.qulingfeng.controller")
public class WebConfig {
    
}
复制代码

在这里与 Spring Boot 的方式不同,我们必须显式定义 @EnableWebMvc 来设置默认的 Spring MVC 配置,而 @ComponentScan 可以指定用于扫描组件的包。
@EnableWebMvc 注解提供了 Spring Web MVC 配置,比如设置 dispatcher servlet、启用 @Controller@RequestMapping 注解以及设置其他默认值。
@ComponentScan 配置组件扫描指令,指定要扫描的包。

初始化类

接下来,我们需要添加一个实现 WebApplicationInitializer 接口的类:

public class AppInitializer implements WebApplicationInitializer {
 
    @Override
    public void onStartup(ServletContext container) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.scan("com.qulingfeng");
        container.addListener(new ContextLoaderListener(context));
 
        ServletRegistration.Dynamic dispatcher = 
          container.addServlet("mvc", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");   
    }
}
复制代码

在这里,我们使用 AnnotationConfigWebApplicationContext 类创建 Spring 上下文,这意味着我们仅使用基于注释的配置。 然后,我们指定要扫描组件和配置类的包。
最后,我们定义 Web 应用程序的入口点 — DispatcherServlet
此类可以完全替换 < 3.0 Servlet 版本中的 web.xml 文件。

XML配置

让我们快速看一下等效的XML web配置:

<context:component-scan base-package="com.qulingfeng.controller" />
<mvc:annotation-driven />
复制代码

我们可以用上面的 WebConfig 类替换这个 XML 文件。
要启动应用程序,我们可以使用一个初始化器类来加载 XML 配置或 web.xml 文件。

结束语

在篇文章中,我们研究了两种用于开发 Spring Web 应用程序的流行方式,一种使用 Spring Boot Web 启动程序,另一种使用核心 spring-webmvc 库。

欢迎关注我的公众号:曲翎风,获得独家整理的学习资源和日常干货推送。
如果您对我的专题内容感兴趣,也可以关注我的博客:sagowiec.com

猜你喜欢

转载自juejin.im/post/5dc41f2c6fb9a04a59016c38