Spring MVC auto-configuratio
官方文档解释
Spring Boot provides auto-configuration for Spring MVC that works well with most applications. he auto-configuration adds the following features on top of Spring’s defaults:
文档 | 解释 |
---|---|
Support for serving static resources, including support for WebJars (covered later in this document)) | 1. 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何 渲染(转发?重定向?)) 2. ContentNegotiatingViewResolver:组合所有的视图解析器的 |
Automatic registration of Converter, GenericConverter, and Formatter beans. | 支持服务静态资源,包括对WebJars的支持 |
Automatic registration of Converter, GenericConverter, and Formatter beans. | 自动注册Converter,GenericConverter和Formatter组件 |
Support for HttpMessageConverters | 支持HttpMessageConverters |
Automatic registration of MessageCodesResolver | 自动注册MessageCodesResolver |
Static index.html support. | 静态index.html。 |
Custom Favicon support | 自定义Favicon |
Automatic use of a ConfigurableWebBindingInitializer bean | 自动使用ConfigurableWebBindingInitializer 实例 |
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. | 如果想保留springboot对springmvc的自动配置部分,并且扩展一些其他的东西,比如拦截器,格式化程序,视图控制器和其他功能,可用通过写配置类的方式,自己进行扩展,但是不能添加@EnableWebMvc |
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc. | 如果 想完全控制Spring MVC,可以使用添加自己的@Configuration 注释@EnableWebMvc |
扩展springMVC功能
@Configuration
//public class MvcConfiguration extends WebMvcConfigurerAdapter { //spring 5.0以前的实现方式
public class MvcConfiguration implements WebMvcConfigurer { //spring 5.0以后的实现方式
/**
* @ Author: WangGQ
* @ Date: 2019/12/24 19:47
* @ Version: 1.0
* @ Description: 配置跨域,解决跨域问题
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/addView").setViewName("imgs/1-1");
}
}