想要了解SpringBoot底层对SpringMVC的自动配置,对SpringMVC进行扩展和定制,可以参照SpringBoot的官方文档,SpringMVC的相关配置都有所记录。
SpringMVC的自动配置
Spring Boot 自动配置好SpringMVC,
Spring Boot对SpringMVC的自动配置:
- Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
- 自动配置了视图解析器(ViewResolver),作用:根据方法的返回值获得试图对象
- ContentNegotiatingViewResolver组合所有的试图解析器。
- 定制视图解析器:给容器中添加一个视图解析器,ContentNegotiatingViewResolver就会自动将其组合进来。
// 测试的viewResolver
@Bean
public ViewResolver myViewResoler() {
return new MyViewResoler();
}
private static class MyViewResoler implements ViewResolver {
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
}
-
Support for serving static resources, including support for WebJars (covered later in this document)).
-
支持静态资源文件夹路径和WebJars
-
Static index.html support.
-
静态首页
-
Custom Favicon support (covered later in this document).
-
图标
-
Automatic registration of Converter, GenericConverter, and Formatter beans.
-
自动注册了转换器、格式化器等
- 类型转换使用Converter组件
- 日期的格式化就要用到格式化器Formatter组件
- 条件是:要在文件中配置日期格式,才会自动注册格式化器Formatter组件,spring.mvc.date-format=dd/MM/yyyy
- 扩展:将自己的转换器或格式化器注册到容器中,自己添加的HttpMessageConverter,值需要将自己的组件注册到容器中(@Bean/@Component)
-
Support for HttpMessageConverters (covered later in this document).
-
SpringMVC用来转换Http请求和响应的。
- 从容器中获取所有的HttpMessageConverter
-
Automatic registration of MessageCodesResolver (covered later in this document).
-
定义代码错误规则的
-
Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
-
初始化web数据绑定器(WebDataBinder),请求数据封装到JavaBean中
spring-boot-autoconfigure-2.1.6.RELEASE.jar\org\springframework\boot\autoconfigure\web:web的所有自动配置场景。
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
扩展SpringMVC
<mvc:view-controller path="/hello" view-name="success" /><!--视图映射-->
<mvc:interceptors><!--拦截器-->
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
编写自己的配置类(使用@Configuration标注的类),是WebMvcConfigurer类型,不能标注@EnableWebMvc注解,既保留了SpringBoot对SpringMVC的自动配置,又有自己的扩展。
示例:
// 使用WebMvcConfigurer可以扩展SpringMVC
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 浏览器发送/caesar请求到success页面
registry.addViewController("/caesar").setViewName("success");
}
}
全面接管SpringMVC
去除Spring Boot 对SpringMVC的自动配置,所有的配置由自己定义,只需要添加一个@EnableWebMvc