4_2.springboot2.x配置之springmvc自動配置


1、Spring MVC auto-configuration

查看官方文檔:

Spring Boot為Spring MVC提供了自動配置,適用於大多數應用程序。
自動配置在Spring的默認值之上添加了以下功能:
1、包含ContentNegotiatingViewResolver 和BeanNameViewResolver beans。

  • 自動配置了ViewResolver(視圖解析器:根據方法的返回值得到視圖對象(View),視圖對象決定如何渲染(轉發?重定向?))

  • ContentNegotiatingViewResolver:組合所有的視圖解析器的;

    我們可以自己給容器中添加一個視圖解析器;自動的將其組合進來

2、支持提供靜態資源,包括對WebJars的支持。
3、自動注冊Converter , GenericConverter 和Formatter beans。

  • Converter:轉換器; public String hello(User user):類型轉換使用Converter

  • Formatter 格式化器; 2017.12.17===Date;

    自己添加的格式化器轉換器,我們只需要放在容器中即可

4、支持HttpMessageConverters

  • Support for HttpMessageConverters (see below).

    • HttpMessageConverter:SpringMVC用來轉換Http請求和響應的;User—Json;

    • HttpMessageConverters 是從容器中確定;獲取所有的HttpMessageConverter;

      自己給容器中添加HttpMessageConverter,只需要將自己的組件注冊容器中(@Bean,@Component)

5、自動注冊MessageCodesResolver 。
6、靜態index.html 支持
7、自定義Favicon 支持
8、自動使用ConfigurableWebBindingInitializer bean

可以配置一個ConfigurableWebBindingInitializer來替換默認的;(添加到容器)

如果你想保留Spring Boot MVC功能,並且你想添加額外的 MVC配置(攔截器,格式化程序,視圖控制器和其他功能),你可以添加自己的@Configuration 類(WebMvcConfigurer )類但沒有 @EnableWebMvc 。如果您希望提供RequestMappingHandlerMapping , RequestMappingHandlerAdapter 或ExceptionHandlerExceptionResolver 的自定義實例,則可以聲明WebMvcRegistrationsAdapter 實例以提供此類組件。
如果您想完全控制Spring MVC,可以添加自己的@Configuration 注釋@EnableWebMvc 。

2、擴展SpringMVC

編寫一個配置類(@Configuration),是WebMvcConfigurer 類型;不能標注@EnableWebMvc

例如:視圖映射功能,瀏覽器發送請求,springboot實現請求到相應頁面,並且通過模板引擎解析

@Configuration//擴展springmvc功能
public class MyMvcConfig implements WebMvcConfigurer {
    //用來做視圖映射
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/index.html").setViewName("login");
        registry.addViewController("/main.html").setViewName("dashboard");
    }
    

原理:WebMvcAutoConfiguration

// Defined as a nested config to ensure WebMvcConfigurer is not read when not
	// on the classpath
	@Configuration
	@Import(EnableWebMvcConfiguration.class)
	@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
	@Order(0)
	public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {

		private static final Log logger = LogFactory.getLog(WebMvcConfigurer.class);

		private final ResourceProperties resourceProperties;

		private final WebMvcProperties mvcProperties;

		private final ListableBeanFactory beanFactory;

		private final ObjectProvider<HttpMessageConverters> messageConvertersProvider;

		final ResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer;

​ 1)、WebMvcAutoConfiguration是SpringMVC的自動配置類

​ 2)、在做其他自動配置時會導入;@Import(EnableWebMvcConfiguration.class)

	public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {

DelegatingWebMvcConfiguration

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

	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,DelegatingWebMvcConfiguration中一個參考實現將所有的WebMvcConfigurer相關配置都來一起調用;

@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		for (WebMvcConfigurer delegate : this.delegates) {
			delegate.configureViewResolvers(registry);
		}
	}

3)、容器中所有的WebMvcConfigurer都會一起起作用;

4)、我們的配置類也會被調用;

​ 效果:SpringMVC的自動配置和我們的擴展配置都會起作用;

3、全面接管SpringMVC

SpringBoot對SpringMVC的自動配置不需要了,所有都是我們自己配置;所有的SpringMVC的自動配置都失效了

我們需要在配置類中添加@EnableWebMvc即可;

//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //瀏覽器發送 /hello 請求來到 success
        registry.addViewController("/hello").setViewName("success");
    }
}

原理:

為什么@EnableWebMvc自動配置就失效了;

1)@EnableWebMvc的核心

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

2)、

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

3)容器中沒有這個組件的時候,這個自動配置類才生效

@Configuration
@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 {

4)、@EnableWebMvc將WebMvcConfigurationSupport組件導入進來;

5)、導入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;

4、如何修改SpringBoot的默認配置

模式:

​ 1)、SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(@Bean、@Component)如果有就用用戶配置的,如果沒有,才自動配置;如果有些組件可以有多個(ViewResolver)將用戶配置的和自己默認的組合起來;

​ 2)、在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴展配置

​ 3)、在SpringBoot中會有很多的xxxCustomizer幫助我們進行定制配置

更多內容請查看官方文檔:https://docs.spring.io/spring-boot/docs/2.1.9.RELEASE/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-auto-configuration


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM