SpringBoot筆記整理(四)

SpringBoot筆記整理(一)
SpringBoot筆記整理(二)
SpringBoot筆記整理(三)
SpringBoot筆記整理(四)

1、SpringMVC自動配置

以下是SpringBoot對SpringMVC

  • nclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
    自動配置了ViewResolver

  • Support for serving static resources, including support for WebJars .

  • registration of Converter, GenericConverter, and Formatter beans.

  • Support for HttpMessageConverters .

  • Automatic registration of MessageCodesResolver .

  • Static index.html support.

  • Custom Favicon support .

  • Automatic use of a ConfigurableWebindingInitializer bean .

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 class of type WebMvcConfigurerAdapter but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping,RequestMappingHandlerAdapter, or ExceptionHandExceptionResolver, 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

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

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

既保留了所有的自動配置,也能用我們擴展的配置

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

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

原理:
1)WebMvcAutoConfiguration是SpringMVC的自動配置類。
2)在做其他自動配置時會導入:@Import(EnableWebMvcConfiguration.class)

@Configuration(
    proxyBeanMethods = false
)
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
    
    
    //從容器中獲取所有的WebMVCConfigurer
    @Autowired(
    required = false
)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
    if (!CollectionUtils.isEmpty(configurers)) {
        this.configurers.addWebMvcConfigurers(configurers);
    }

}

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

4)我們的配置類也會被調用
效果:SpringMVC的自動配置和我們的拓展配置都會起作用

3、全面接管SpringMVC

SpringBoot對SpringMVC的自動配置不需要了,所有的都是我們自己配置,所有的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");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章