啟用 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 和其他格式的有效載荷轉換器)。