SpringMVC自动配置
Springboot已经为我们自动配置好了SpringMVC
一下是Springboot对SpringMVC的默认配置
1.Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
- 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定
如何渲染(转发?重定向?。。。)) - ContentNegotiatingViewResolver:组合所有的视图解析器
- 如何定制:我们可以自己给容器中添加一个视图解析器;自动将其组合进来;
2.Support for serving static resources,including support for Webjars(see below).静态资源文件夹路径
,Webjars
3. Static index.html support.静态首页访问
4.Custom Favicon support(see below). favicon.ico
5.自动注册了 of Converter , GenericConverter , Formatter beans.
- Converter :转换器:public String hello (User user):类型转换使用Converter
- Formatter 格式化器:2020.6.13 === Date;
@Bean
//在文件中配置日期格式化的规则
@ConditionalOnProperty(prefix = "spring.mvc",name = "date-format")
public Formatter<Date> dateFormatter(){
//日期格式化组件
return new DateFormatter(this.mvcProperties.getDateFormat())
}
自己添加的格式化转换器,我们只需要放在容器中即可
6.Support for HttpMessageCoverters(see below)
- HttpMessageCoverters:SpringMVC用来转换Http请求和响应的;User----》Json;
- HttpMessageCoverters是从容器中确定;获取所有的HttpMessageCoverter;
自己给容器中添加HttpMessageCoverter,只需将自己的组件注册容器中(@Bean, @Compent)
7.Automatic registration of MessageCodesResolver (see below).定义错误代码生成规则
扩展SpringMVC
<mvc:view-controller path = "/XX" view-name = "XXX"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path = "/XX" />
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
边写一个配置类(@Configuration),是WebMvcConfigurer类型;不能标注@EnableWebMvc
既保留了所有的自动配置,也能自定义扩展配置;
package com.Slgod.springboot.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter{
@Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/Slgod").setViewName("Slgod");
}
}
全面接管SpringMVC
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了
我们需要在配置类中添加@EnableWebMvc注解即可;
原理:
为什么添加@EnableWebMvc自动配置就失效?
1)@EnableWebMvc的核心
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class,DispatcherServlet.class,WebMvcConfigurerAdapter.class})
//容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE+10)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class,ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {