Bootstrap

SpringBoot进阶篇

今天的博客主题

       SpringBoot ——》SpringBoot进阶篇


springBoot是如何整合springMVC

1)回顾下什么是springMVC

SpringMVC 全称(Spring Web MVC框架)是一个丰富的“模型-视图-控制器”Web框架。

SpringMVC使您可以创建特殊的@Controller或@RestController Bean来处理传入的HTTP请求。

控制器中的方法使用@RequestMapping注释映射到HTTP。

SpringMVC是Spring框架核心的一部分。

SpringBoot对spring框架做的封装,自然要为springMVC做封装进行自动装配。

 

2)SpringMVC的自动装配

SpringBoot为SpringMVC提供了自动配置,可以很好地与大多数应用程序配合使用。

自动配置在Spring默认设置的基础上增加了以下特性:

1)包含 ContentNegotingViewResolver 和 BeanNameViewResolver(两个试图解析器)

2)支持服务静态资源和WebJars

3)自动注册Converter,GenericConverter,Formatter

4)支持httpMessageConverter

5)自动注册MessageCodesResolver

6)静态index.html(设置首页)

7)自定义Favicon支持(图标支持)

8)自动使用可配置的WebBindingInitializerbean

 

如果想保留Spring Boot MVC特性,并且只想添加额外的MVC配置(比如:拦截器、格式化程序、视图控制器等),只需要添加一个类型为WebMvcConfigurerAdapter的@Configuration类,但不添加@EnableWebMvc。如果希望提供RequestMappingHandlerMapping,RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定义实例,则可以声明一个提供此类组件的WebMvcRegistrationsAdapter实例。

如果要完全控制 SpringMVC,在自定义的 @Configuration 配置类 增加 @EnableWebMvc 注解

看来springBoot控制的很好,你要觉得我不行,你自己来。

WebMvcAutoConfiguration 就是对 SpringMVC 自动装配类。

新增的组件特性,上面也提到了。可以对照看下

 

扩展springMVC在《springboot入门篇(二)》也都有示例。

 

3)全面自己控制SpringMVC

为什么加个 @EnableWebMvc 注解标识到配置类,就导致springboot装配的MVC失效呢?

原理剖析:

在这个注解上通过Import注解导入:DelegatingWebMvcConfiguration 组件

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
    ...
}

DelegatingWebMvcConfiguration是WebMvcConfiurationSupport(只保证了springmvc的基本功能)类型的。

回头看下WebMvcAutoConfiguration

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
// 容器中没有WebMvcConfigurationSupport该配置文件才生生效,但是使用了@EnableWebMvc,就会导入WebMvcConfiurationSuppor 
// 只保存了springmvc的最基本的功能
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
      ValidationAutoConfiguration.class })
pu
;