SpringBoot(五)——————SpringMvc自动配置原理

参考文档:https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/html/spring-boot-features.html#boot-features-developing-web-applications

  • SpringMvc自动配置原理

Spring Boot为Spring MVC提供了自动配置,可与大多数应用程序完美配合。自动配置在Spring的默认值之上添加了以下功能:

  • 包含ContentNegotiatingViewResolverBeanNameViewResolver

自动配置了视图解析器ViewResolver,根据方法返回值得到视图对象(View),视图对象决定如何渲染,转发?重定向?

ContentNegotiatingViewResolver作用组合所有的视图解析器

可以自己定义视图解析器并添加到容器中,ContentNegotiatingViewResolver自动将其组合进来

 

 

  • 支持服务静态资源,包括对WebJars的支持。静态资源文件夹

		@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry) {
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
			CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
			if (!registry.hasMappingForPattern("/webjars/**")) {
				customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
		}
  • 自动注册ConverterGenericConverterFormatter豆类。

    Converter:转换器,类型转换,页面传递的参数和controller方法接收的VO对象数据类型的转换

    Formatter:格式化器,将字符串转成格式化的日期类型

  • 支持HttpMessageConverters

    HttpMessageConverters:SpringMvc用来转换http请求和响应的,比如将实体对象转换成JSON

    从容器中获取所有的HttpMessageConverters ,也可以自定义HttpMessageConverters然后放入容器中

  • 自动注册MessageCodesResolver

    MessageCodesResolver:定义错误代码生成规则

  • 静态index.html支持。静态首页访问

  • 定制Favicon支持,自定义网页小图标

  • 自动使用ConfigurableWebBindingInitializerbean

    ConfigurableWebBindingInitializer:初始化WebDataBinder Web数据绑定器,请求数据与VO对象进行绑定

    SpringBoot在web下所有自动配置类在org.springframework.boot.autoconfigure.web这个路径全部列举

SpringMvc扩展

如果您想保留Spring Boot MVC功能,并且想要添加其他MVC配置(拦截器,格式化程序,视图控制器和其他功能),则可以添加自己@Configuration的type类,WebMvcConfigurer不添加 @EnableWebMvc。如果您希望提供,或的自定义实例RequestMappingHandlerMapping,则可以声明一个实例来提供此类组件。RequestMappingHandlerAdapter``ExceptionHandlerExceptionResolver``WebMvcRegistrationsAdapter

如果您想完全控制Spring MVC,可以使用添加自己的@Configuration注释@EnableWebMvc

  • 总结:

1)、SpringMvc扩展实现WebMvcConfigurer接口添加自己要添加的方法和配置

2)、WebMvcConfigurerAdapter:SpringBoot2.0以后WebMvcConfigurerAdapter被弃用,继承这个类自动配置都生效,自己重写的方法也会生效。

WebMvcConfigurationSupport:如果继承WebMvcConfigurationSupport,SpringMvc的自动配置都失效,自己重写的方法会生效

@EnableWebMvc这个注解标记后,自动配置失效,重写的方法失效。SpringBoot中Springmvc的一套都无效。

  • SpringBoot2.2以后就弃用了WebMvcConfigurerAdapter,需要扩展就实现WebMvcConfigurer

    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
    ​
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/abc").setViewName("hello");
        }
  1. 如果标注了@EnableWebMvc这个注解那么SpringBoot的Springmvc将全部失效。自己写的配置全面接管SpringMvc,​​​​​​​

@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {}
@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
}
  • 如何修改SpringBoot的默认配置

1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;

2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置

3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置

发布了101 篇原创文章 · 获赞 10 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/WMY1230/article/details/103724060