SpringBoot系列十一:SpringMVC自动配置

一、SpringMVC自动配置
 SpringBoot 自动配置好了 SpringMVC。相应的配置都在 WebMvcAutoConfiguration 类中。官方网站:https://docs.spring.io/spring/docs/4.3.14.RELEASE/spring-framework-reference/htmlsingle#mvc。 以下是 SpringBoot 对 SpringMVC 的默认配置:
 1、Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans。自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发或重定向))。
 2、ContentNegotiatingViewResolver:组合所有的视图解析器的;如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来。

@SpringBootApplication
public class SpringBoot04WebRestfulcrudApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot04WebRestfulcrudApplication.class, args);
    }

    // 自定义视图解析器
    @Bean
    public ViewResolver myViewReolver(){
        return new MyViewResolver();
    }

    public static class MyViewResolver implements ViewResolver{

        @Override
        public View resolveViewName(String viewName, Locale locale) throws Exception {
            return null;
        }
    }
}

 3、 Support for serving static resources, including support for WebJars (see below)。静态资源文件夹路径,webjars
 4、Static index.html support 静态首页访问。
 5、Custom Favicon support (see below)。 favicon.ico
 6、自动注册了 of Converter, GenericConverter, Formatter beans。Converter:类型转换器; Formatter 格式化器; 如:将 2017.12.17 转换成 Date。

@Bean
@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format") //在文件中配置日期格式化的规则
public Formatter<Date> dateFormatter() {
	return new DateFormatter(this.mvcProperties.getDateFormat()); //日期格式化组件
}

自己添加的格式化器转换器,我们只需要放在容器中即可。
 7、Support for HttpMessageConverters (see below)。HttpMessageConverter:SpringMVC用来转换Http请求和响应的;HttpMessageConverters 是从容器中确定;获取所有的HttpMessageConverter。自己给容器中添加HttpMessageConverter,只需要将自己的组件注册容器中。
 8、Automatic registration of MessageCodesResolver (see below)。定义错误代码生成规则。
 9、Automatic use of a ConfigurableWebBindingInitializer bean (see below)。 用来初始化 WebDataBinder,如:将请求数据绑定到 JavaBean;我们可以配置一个ConfigurableWebBindingInitializer 并添加到容器中来替换默认的。
org.springframework.boot.autoconfigure.web:web的所有自动场景。

二、扩展SpringMVC

<mvc:view-controller path="/hello" view-name="success"/>
	<mvc:interceptors>
	    <mvc:interceptor>
	        <mvc:mapping path="/hello"/>
	        <bean></bean>
	    </mvc:interceptor>
	</mvc:interceptors>

 编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc。既保留了所有的自动配置,也能用我们扩展的配置;

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //浏览器发送 /atguigu 请求来到 success
        registry.addViewController("/atguigu").setViewName("success");
    }
}

原理:
 1、WebMvcAutoConfiguration 是SpringMVC的自动配置类。
 2、@Import(EnableWebMvcConfiguration.class)。在做其他自动配置时会导入 EnableWebMvcConfiguration。

 @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相关配置都来一起调用;  
           	@Override
            // public void addViewControllers(ViewControllerRegistry registry) {
             //    for (WebMvcConfigurer delegate : this.delegates) {
              //       delegate.addViewControllers(registry);
              //   }
             }
         }
}

 3、容器中所有的WebMvcConfigurer都会一起起作用。
 4、我们的配置类也会被调用;SpringMVC 的自动配置和我们的扩展配置都会起作用。

三、全面接管SpringMVC
 SpringBoot 对 SpringMVC 的自动配置就失效了,所有的都需要我们自己去配置;只需要在配置类中添加@EnableWebMvc 即可。

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @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 {
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

2、自动配置类 WebMvcAutoConfiguration 上有一个注解:@ConditionalOnMissingBean(WebMvcConfigurationSupport.class) 。表示当容器中没有这个组件(WebMvcConfigurationSuppor)的时候,这个自动配置类(WebMvcAutoConfiguration )才生效。

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class) //容器中没有这个组件的时候,这个自动配置类才生效
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

3、@EnableWebMvc 将 WebMvcConfigurationSupport 组件导入进来了。
4、导入的 WebMvcConfigurationSupport 只是SpringMVC最基本的功能。

四、修改 SpringBoot 的默认配置
 1、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来。
 2、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置。
 3、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置。

猜你喜欢

转载自blog.csdn.net/lizhiqiang1217/article/details/91355658