1. 概述
本文将展示如何使用Spring创建Web应用程序。
我们会分别介绍两种方案:
- 使用Spring Boot快速构建
- 使用传统Spring MVC手动配置
主要采用Java配置方式,也会简要对比XML配置方案。
2. 使用Spring Boot搭建
2.1 Maven依赖
首先添加核心依赖spring-boot-starter-web
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
该starter自动包含:
- ✅
spring-web
和spring-webmvc
模块 - ✅ 嵌入式Tomcat服务器(无需单独安装)
2.2 创建Spring Boot应用
最简单的方式是创建主类并添加@SpringBootApplication
注解:
@SpringBootApplication
public class SpringBootRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestApplication.class, args);
}
}
这个注解相当于组合使用了:
@Configuration
@EnableAutoConfiguration
@ComponentScan
默认会扫描当前包及其子包下的所有组件。
对于Java配置,我们还需要创建一个配置类:
@Configuration
public class WebConfig {
}
@Configuration
注解是Spring Java配置的核心,它本身被@Component
注解标记,因此也会被组件扫描发现。该类的主要作用是为Spring IoC容器提供Bean定义源。
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
@EnableWebMvc
@ComponentScan(basePackages = "com.baeldung.controller")
public class WebConfig {
}
⚠️ 与Spring Boot方案不同,这里需要显式声明:
@EnableWebMvc
:启用Spring MVC默认配置@ComponentScan
:指定组件扫描包路径
@EnableWebMvc
会自动配置:
- DispatcherServlet
@Controller
和@RequestMapping
注解支持- 其他MVC默认组件
3.3 初始化类
需要实现WebApplicationInitializer
接口:
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.scan("com.baeldung");
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher =
container.addServlet("mvc", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
关键步骤:
- 创建基于注解的Spring上下文
- 指定组件扫描路径
- 注册
ContextLoaderListener
- 配置
DispatcherServlet
作为入口点
这个类完全替代了Servlet 3.0之前的web.xml
文件。
4. XML配置方案
等效的XML配置如下:
<context:component-scan base-package="com.baeldung.controller" />
<mvc:annotation-driven />
可以完全替代前面的WebConfig
类。
启动应用时,可以通过:
- 加载XML配置的Initializer类
- 传统的
web.xml
文件
5. 结论
本文介绍了两种Spring Web应用的搭建方案:
- Spring Boot方案:简单粗暴,自动配置
- 传统Spring MVC方案:手动配置,更灵活
在下一篇文章中,我们将深入探讨:
- MVC项目配置
- HTTP状态码处理
- 数据序列化
- 内容协商
本文所有代码示例可在GitHub获取,这是一个标准Maven项目,可直接导入运行。