springboot為SpringMVC配置了自動配置,以下是SpringBoot對SpringMVC的默認配置
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
自動配置在Spring的默認配置之上添加了以下功能
- 包含
ContentNegotiatingViewResolver
和BeanNameViewResolver
。--> 視圖解析器 - 支持服務靜態資源,包括對WebJars的支持(官方文檔中有介紹)。--> 靜態資源文件夾路徑
- 自動注冊
Converter
,GenericConverter
和Formatter
beans。--> 轉換器,格式化器 - 支持
HttpMessageConverters
(官方文檔中有介紹)。--> SpringMVC用來轉換Http請求和響應的; - 自動注冊
MessageCodesResolver
(官方文檔中有介紹)。--> 定義錯誤代碼生成規則 - 靜態
index.html
支持。--> 靜態首頁訪問 - 定制
Favicon.ioc
支持(官方文檔中有介紹)。--> 網站圖標 - 自動使用
ConfigurableWebBindingInitializer
bean(官方文檔中有介紹)。
如果您想保留 Spring Boot MVC 的功能,并且需要添加其他?MVC 配置(攔截器,格式化程序和視圖控制器等),可以添加自己的?WebMvcConfigurer
?類型的?@Configuration
?類,但不能帶?@EnableWebMvc
?注解。如果您想自定義?RequestMappingHandlerMapping
、RequestMappingHandlerAdapter
?或者?ExceptionHandlerExceptionResolver
?實例,可以聲明一個?WebMvcRegistrationsAdapter
?實例來提供這些組件。如果您想完全掌控 Spring MVC,可以添加自定義注解了?@EnableWebMvc
?的 @Configuration 配置類。
視圖解析器
視圖解析器:根據方法的返回值得到視圖對象(View),視圖對象決定如何渲染(轉發?重定向?)
- 自動配置了ViewResolver
- ContentNegotiatingViewResolver:組合所有的視圖解析器的;
轉換器/格式化器
Converter
:轉換器; public String hello(User user):類型轉換使用Converter(表單數據轉為user)Formatter
?格式化器; 2017.12.17===Date;
@Bean//在配置文件中配置日期格式化的規則@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")public Formatter<Date> dateFormatter() {return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化組件}
自己添加的格式化器轉換器,我們只需要放在容器中即可
HttpMessageConverters
HttpMessageConverter
:SpringMVC用來轉換Http請求和響應的;User---Json;HttpMessageConverters
?是從容器中確定;獲取所有的HttpMessageConverter;-
自己給容器中添加HttpMessageConverter,只需要將自己的組件注冊容器中(@Bean,@Component)
MessageCodesResolver
我們可以配置一個ConfigurableWebBindingInitializer來替換默認的;(添加到容器)
擴展SpringMVC
- 先前的配置文件的配置
<mvc:view-controller path="/hello" view-name="success"/>
- 使用配置類(@Configuration)是WebMvcConfigurer類型,不能標注@EnableWebMvc
@Configuration public class MyMvcConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/hi").setViewName("success");} }
如何修改SpringBoot的默認配置
SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(@Bean、@Component)如果有就用戶配置的,如果沒有,才自動配置;如果有些組件可以有多個(ViewResolver)將用戶配置的和自己默認的組合起來;
- 在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴展配置
- 在SpringBoot中會有很多的xxxCustomizer幫助我們進行定制配置
?