使用Spring 5创建Web应用程序
1.概述
本教程说明了如何使用 Spring 创建 Web 应用程序。我们将研究用于构建应用程序的 Spring Boot 解决方案,并查看非 Spring Boot 方法。我们将主要使用 Java 配置,但也会看看它们等效的 XML 配置。
2. 使用 Spring Boot 进行设置
2.1. Maven 依赖
首先,我们需要spring-boot-starter-web 依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.1</version>
</dependency>
该启动器包括:
- spring-web和 Spring Web 应用程序所需的spring-webmvc模块
- 一个 Tomcat 启动器,这样我们就可以直接运行我们的 Web 应用程序,而无需显式安装任何服务器
2.2. 创建一个 Spring Boot 应用程序
**开始使用 Spring Boot 最直接的方法是创建一个主类并使用 @SpringBootApplication **对其进行注释:
@SpringBootApplication
public class SpringBootRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestApplication.class, args);
}
}
这个单一注解等效于使用*@Configuration*、@EnableAutoConfiguration和*@ComponentScan*。 默认情况下,它将扫描同一包或以下的所有组件。 接下来,对于 Spring bean 的基于 Java 的配置,我们需要创建一个配置类并使用@Configuration*注解对其进行注解*:
@Configuration
public class WebConfig {
}
这个注解是基于 Java 的 Spring 配置使用的主要工件;它本身使用*@Component*进行注释,这使得带注释的类成为标准 bean,因此也是组件扫描的候选对象。
@Configuration类的主要目的是作为 Spring IoC 容器的 bean 定义的来源。更详细的描述请参见官方文档 。 让我们也看看使用核心spring-webmvc库的解决方案。
3. 使用 spring-webmvc 进行设置
3.1. Maven 依赖项
首先,我们需要spring-webmvc 依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.3</version>
</dependency>
3.2. 基于 Java 的 Web 配置
接下来,我们将添加具有*@Configuration*注解的配置类:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.blogdemo.controller")
public class WebConfig {
}
在这里,与 Spring Boot 解决方案不同,我们必须显式定义@EnableWebMvc 以设置默认 Spring MVC 配置和 @ComponentScan 以指定要扫描组件的包。**
@EnableWebMvc注解提供Spring Web MVC 配置,例如设置调度程序 servlet、启用*@Controller和@RequestMapping*注解以及设置其他默认值。 @ComponentScan配置组件扫描指令,指定要扫描的包。
3.3. 初始化器类
接下来,我们需要添加一个实现WebApplicationInitializer接口的类:
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.scan("com.blogdemo");
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文件。
4. XML 配置
让我们快速看一下等效的 XML Web 配置:
<context:component-scan base-package="com.blogdemo.controller" />
<mvc:annotation-driven />
我们可以用上面的WebConfig类替换这个 XML 文件。
要启动应用程序,我们可以使用加载 XML 配置或 web.xml 文件的 Initializer 类。有关这两种方法的更多详细信息,请查看之前的文章 。