Skip to content

启用 MVC 配置

你可以使用 @EnableWebMvc 注解来通过编程方式启用 MVC 配置,或者使用 <mvc:annotation-driven> 进行 XML 配置。

java
@Configuration
@EnableWebMvc
public class WebConfiguration {
}
kotlin
@Configuration
@EnableWebMvc
class WebConfiguration {
}
xml
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:mvc="http://www.springframework.org/schema/mvc"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xsi:schemaLocation="
			http://www.springframework.org/schema/beans
			https://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/mvc
			https://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<mvc:annotation-driven/>

</beans>

警告

从 Spring Framework 7.0 开始,Spring MVC 的 XML 配置命名空间已被弃用。目前还没有完全移除它的计划,但 XML 配置将不再更新以同步 Java 配置模型的新功能。

提示

在使用 Spring Boot 时,你可能希望使用 WebMvcConfigurer 类型的 @Configuration 类,但不带 @EnableWebMvc 注解,以保留 Spring Boot 的 MVC 自动配置。详见 MVC 配置 API 章节或 Spring Boot 官方文档

上述配置会注册许多 Spring MVC 基础设施 Bean,并根据类路径上的依赖项自动调整(例如,自动注册用于 JSON、XML 等的内容转换器)。


补充教学

1. @EnableWebMvc 到底做了什么?

当你添加 @EnableWebMvc 时,Spring 会导入 DelegatingWebMvcConfiguration。这个类会:

  • 注册 RequestMappingHandlerMappingRequestMappingHandlerAdapterExceptionHandlerExceptionResolver 等核心组件。
  • 根据类路径加载消息转换器(Jackson, Gson, JAXB 等)。
  • 允许通过 WebMvcConfigurer 接口参与到这些组件的自定义过程中。

2. 为什么 Spring Boot 建议不加 @EnableWebMvc?

如果你在 Spring Boot 中加上了 @EnableWebMvc,表示你要全权接管 MVC 配置。Spring Boot 提供的所有自动配置(如默认的静态资源处理、错误页面映射、预设的日期格式化器等)都会失效。只有在你确实需要完全重写配置时才考虑添加它。

Based on Spring Framework.