启用 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 和其他格式的有效载荷转换器)。