启用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>
注意
从版本7.0开始,Spring MVC对XML配置命名空间的支持已被弃用。目前还没有计划完全移除这一功能,但XML配置将不再会更新以遵循Java配置模型。
备注
在使用 Spring Boot 时,你可能希望使用类型为 WebMvcConfigurer 的 @Configuration 类,但不要使用 @EnableWebMvc,以便保留对 Spring Boot MVC 的自定义设置。更多详细信息请参阅 MVC 配置 API 部分 以及 专门的 Spring Boot 文档。
前面的例子注册了一些Spring MVC基础设施bean,并适应了类路径上可用的依赖项(例如,JSON、XML等的负载转换器)。