spring-boot-SpringMVC自動配置
1.Spring MVC auto-conmfiguration
SpringBoot自動配置好了SpringMVC
以下是SpringBoot對SpringMVC的預設配置:(WebMvcConfiguration)
- Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.
a.自動配置了ViewResolver(檢視解析器:根據方法的返回值得到檢視物件(View),檢視物件決定如何渲染(轉發?重定向))
b.ContentNegotiatingViewResolver:組合所有的檢視解析器的;
原始碼:
@Override protected void initServletContext(ServletContext servletContext) { Collection<ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(getApplicationContext(), ViewResolver.class).values(); if (this.viewResolvers == null) { this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.size()); for (ViewResolver viewResolver : matchingBeans) { if (this != viewResolver) { this.viewResolvers.add(viewResolver); } } }
從BeanFactoryutils中獲取所有的檢視解析器,把這個檢視解析作為他要組合的所有檢視解析器
- Support for serving static resources, including support for WebJars (covered later in this document)).靜態資原始檔夾路徑 webjars
- Automatic registration of
Converter
,GenericConverter
, andFormatter
beans.
a.Converter:轉換器;public String hello(User user);型別轉換使用Converter
b.Formatter:格式化器;日期2017.12.17===Date;
c.如何定製:我們可以自己給容器中新增一個檢視解析器;自動將其組合起來。
@Bean
@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在檔案中配置日期格式的規則
public Formatter<Date> dateFormatter() {
return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化元件
}
- Support for
HttpMessageConverters
(covered later in this document).
a.HttpMessageConverters:SpringMVC用來轉換Http請求和響應;User===json
b.HttpMessageConverters:是從容器中確定;獲取所有的HttpMessageConverters;自己給容器中添
加 HttpMessageConverters ,只需要將自己的元件註冊到容器中(@Bean,@Component)
- Automatic registration of
MessageCodesResolver
(covered later in this document). - Static
index.html
support. 靜態首頁訪問 - Custom
Favicon
support (covered later in this document). favicon.ico - Automatic use of a
ConfigurableWebBindingInitializer
bean (covered later in this document).
我們可以配置一個ConfigurableWebBindingIitalizer來替換預設的;(新增到容器)
初始化WebDataBinder;
請求資料======javaBean;
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
.
2.擴充套件SpringMVC
之前SpringMVC的配置
<mvc:view‐controller path="/hello" view‐name="success"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
編寫一個配置類(@Configuration)是WebMvcConfigurerAdater型別;不能標註@EnableWebMvc;
既保留了所有的自動配置,也能用我們擴充套件的配置
package com.hbsi.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.hbsi.component.LoginHandlerIntercepter;
import com.hbsi.component.MyLocaleResovler;
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter{
//既保留了所有的自動配置,也能用我們擴充套件的配置
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//瀏覽器傳送/zch請求到success
registry.addViewController("/zch").setViewName("success");
}
//所有的WebMvcConfigurerAdapter元件都會一起使用
@Bean //將元件註冊在容器
public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
WebMvcConfigurerAdapter webMvcConfigurerAdapter = new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//瀏覽器傳送/zch請求到success
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
// registry.addViewController("/main.html").setViewName("dashboard");
}
//註冊攔截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//靜態資源 *.css,*.js
//SpringBoot已經做好了靜態資源對映 /**攔截所有
registry.addInterceptor(new LoginHandlerIntercepter()).addPathPatterns("/**")
.excludePathPatterns("/","index.html","/user/login");
}
};
return webMvcConfigurerAdapter;
}
}
原理:
1).WebMvcAutoConfiguration是SpringMVC的自動配置類
2).在做其他自動配置時會匯入;@Import(EnableWebMvcConfiguration.class)
@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
//從容器中獲取所有的WebMvcConfigurer
@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
//一個參考實現;將所有的WebMvcConfigurer相關配置都來一起呼叫;
// public void addViewControllers(ViewControllerRegistry registry) {
// for (WebMvcConfigurer delegate : this.delegates) {
// delegate.addViewControllers(registry);
//
// }
}
}
}
3)容器中所有的WebMvcConfigurer都會一起使用
4)我們的配置類也會被呼叫;
效果:SpringMVC的自動配置和我們的擴充套件配置都會起作用
3.全面接管SpringMVC
SpringBoot對SpringMVC的自動配置不需要了,所有都是我們自己的配置;所有的SpringMVC的自動配置失效了
我們需要在配置類中新增@EnableWebMvc即可
//使用WebMvcConfigurerAdapter可以來擴充套件SpringMVC的功能
@EnableWebMvc
@Configuration publicclassMyMvcConfigextendsWebMvcConfigurerAdapter{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//瀏覽器傳送 /atguigu 請求來到 success
registry.addViewController("/atguigu").setViewName("success");
}
}
原理:
為什麼@EnableWebMvc自動配置失效了;
1)@EnableWebMvc的核心
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc{
2)
@Configuration
publicclassDelegatingWebMvcConfigurationextendsWebMvcConfigurationSupport{
3)
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({Servlet.class,DispatcherServlet.class,
WebMvcConfigurerAdapter.class })
//容器中沒有這個元件的時候,這個自動配置類才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE+10)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
publicclassWebMvcAutoConfiguration{
4)@EnableWebMvc將WebMvcConfigurationSupport元件匯入進來
5) 匯入的WebMvcConfiguraionSupport只是SpringMVC最基本的功能。 檢視解析器 攔截器都得自己配