源码分析----SpringBoot中SpringMVC配置原理
作者:互联网
官方文档
29.1.1 Spring MVC Auto-configuration
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
The auto-configuration adds the following features on top of Spring’s defaults:
- Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.- 自动配置ViewResolver(视图解析器:根据方法的返回值获得视图对象(View),视图对象决定如何渲染(转发?重定向?))
- ContentNegotiatingViewResolver组合了所有的视图解析器
- 如何定制?我们只需要给容器添加一个视图解析器,自动回将其组合进来
- Support for serving static resources, including support for WebJars (covered later in this document)).
- Automatic registration of
Converter
,GenericConverter
, andFormatter
beans.- Converter:转换器,比如public String test(User user);表单中传入的数字,true/false等都是文本,这些文本需要映射到User中,需要转换器,进行类型转换,将text(数字)-->int/integer,text(true)-->bool
Formatter
:格式化,2017/0/101--->Date
- Support for
HttpMessageConverters
(covered later in this document).- HttpMessageConverters:是SpringMVC用来http请求和响应的,比如将User--->json返回
- HttpMessageConverters是从容器中确定的
- Automatic registration of
MessageCodesResolver
(covered later in this document). - Static
index.html
support. - Custom
Favicon
support (covered later in this document). - Automatic use of a
ConfigurableWebBindingInitializer
bean (covered later in this document).
Spring Boot扩展 SpringMVC功能
在spring MVC中,我们可以编写xml来配置我们需要的一些功能,比如拦截器等等。
you can add your own @Configuration
class of type WebMvcConfigurer
but without @EnableWebMvc
我们可以在类型是WebMvcConfigurer的类上使用@Configuration注解,并且实现我们需要的方法;
@Configuration public class MyMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor("拦截器对象").addPathPatterns("/hellow"); } }
Spring Boot全面接管SpringMVC功能
@EnableWebMvc @Configuration public class MyMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { } }
为什么加上@EnableWebMvc注解后spring mvc就是失效了呢?
1、导入DelegatingWebMvcConfiguration
@Import(DelegatingWebMvcConfiguration.class) public @interface EnableWebMvc { }
2、DelegatingWebMvcConfiguration 继承了 WebMvcConfigurationSupport
@Configuration public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
3、查看 WebMvcAutoConfiguration 源码
@Configuration @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class }) //条件判断,组件中有没有WebMvcConfigurationSupport,没有才自动配置 @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10) @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class }) public class WebMvcAutoConfiguration {
标签:SpringBoot,SpringMVC,Spring,视图,class,源码,covered,Configuration,public 来源: https://www.cnblogs.com/yanxiaoge/p/11357512.html