启用 MVC 配置

您可以使用 @EnableWebMvc 注解启用编程式的 MVC 配置,或者使用 <mvc:annotation-driven> 进行 XML 配置,如下例所示

  • Java

  • Kotlin

  • Xml

@Configuration
@EnableWebMvc
public class WebConfiguration {
}
@Configuration
@EnableWebMvc
class WebConfiguration {
}
<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 Boot 时,您可能希望使用类型为 WebMvcConfigurer@Configuration 类,但不带 @EnableWebMvc 注解,以保留 Spring Boot 的 MVC 自定义配置。更多详细信息请参阅MVC 配置 API 部分以及相关的 Spring Boot 文档

前面的示例注册了许多 Spring MVC 的基础设施 Bean,并根据类路径中可用的依赖(例如,JSON、XML 及其他类型的负载转换器)进行调整。