尚硅谷springboot学习23-SpringMVC配置

  1. Spring MVC auto-configuration  

  以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration)

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

    • 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向?))
    • ContentNegotiatingViewResolver:组合所有的视图解析器的;
    • 如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来;
  • Support for serving static resources, including support for WebJars (see below).静态资源文件夹路径,webjars
  • Static index.html support. 静态首页访问
  • Custom Favicon support (see below). favicon.ico

  自动注册了 of Converter, GenericConverter, Formatter beans.

  • Converter:转换器; public String hello(User user):类型转换使用Converter
  • Formatter 格式化器; 2017.12.17===Date;
    @Bean
        @ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在文件中配置日期格式化的规则
        public Formatter<Date> dateFormatter() {
            return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化组件
        }

  自己添加的格式化器转换器,我们只需要放在容器中即可

  Support for HttpMessageConverters (see below).

  • HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User---Json;
  • HttpMessageConverters 是从容器中确定;获取所有的HttpMessageConverter;

    自己给容器中添加HttpMessageConverter,只需要将自己的组件注册容器中(@Bean,@Component)

  • Automatic registration of MessageCodesResolver (see below).定义错误代码生成规则
  • Automatic use of a ConfigurableWebBindingInitializer bean (see below).

    我们可以配置一个ConfigurableWebBindingInitializer来替换默认的;(添加到容器)

初始化WebDataBinder;
请求数据=====JavaBean;

  org.springframework.boot.autoconfigure.web:web的所有自动场景;

  If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing 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),是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)

@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的自动配置和我们的扩展配置都会起作用;

  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");
    }
}

  原理:

  为什么@EnableWebMvc自动配置就失效了;

  1)@EnableWebMvc的核心

@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {

  2)、

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

  3)、

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

  4)、@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;

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

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

  模式:

?   1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;

?   2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置

?   3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置

原文地址:https://www.cnblogs.com/liunianfeiyu/p/10355771.html

时间: 2024-08-01 12:40:53

尚硅谷springboot学习23-SpringMVC配置的相关文章

尚硅谷springboot学习14-自动配置原理

配置文件能配置哪些属性 配置文件能配置的属性参照 自动配置的原理 1).SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration 2).@EnableAutoConfiguration 作用: 利用EnableAutoConfigurationImportSelector给容器中导入一些组件? 可以查看selectImports()方法的内容: List<String> configurations = getCandidateConfi

尚硅谷springboot学习18-日志使用

默认配置 SpringBoot默认帮我们配置好了日志 //记录器 Logger logger = LoggerFactory.getLogger(getClass()); @Test public void contextLoads() { //System.out.println(); //日志的级别: //由低到高 trace<debug<info<warn<error //可以调整输出的日志级别:日志就只会在这个级别以以后的高级别生效 logger.trace("这

尚硅谷springboot学习5-主入口类说明

package com.atguigu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用 */ @SpringBootApplication public class HelloWorldM

尚硅谷springboot学习6-eclipse创建springboot项目的三种方法(转)

方法一 安装STS插件 安装插件导向窗口完成后,在eclipse右下角将会出现安装插件的进度,等插件安装完成后重启eclipse生效 新建spring boot项目 项目启动 方法二 1.创建Maven项目 2.选择项目类型 3.选择项目 4.编写项目组和名称-finish即可 5.修改pom.xml文件 <!-- spring boot基本环境 --> <parent> <groupId>org.springframework.boot</groupId>

尚硅谷springboot学习7-yaml配置文件

SpringBoot使用一个全局的配置文件,配置文件名是固定的: application.properties application.yml 配置文件的作用:修改SpringBoot自动配置的默认值:SpringBoot在底层都给我们自动配置好: YAML(YAML Ain't Markup Language) ? YAML A Markup Language:是一个标记语言 ? YAML isn't Markup Language:不是一个标记语言: 标记语言: ? 以前的配置文件:大多都使

尚硅谷springboot学习9-配置文件值注入

首先让我想到的是spring的依赖注入,这里我们可以将yaml或者properties配置文件中的值注入到java bean中 配置文件 person: lastName: hello age: 18 boss: false birth: 2017/12/12 maps: {k1: v1,k2: 12} lists: - lisi - zhaoliu dog: name: 小狗 age: 12 javaBean: package com.atguigu.springboot.bean; impo

尚硅谷springboot学习[email&#160;protected],@ImportResource,@Bean

@PropertySource 使用指定的属性文件而不一定是application.xxx 同样可以注入相关内容 @ImportResource 导入Spring的配置文件,让配置文件里面的内容生效: Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别: 想让Spring的配置文件生效,加载进来:@ImportResource标注在一个配置类上 @Bean SpringBoot推荐给容器中添加组件的方式:推荐使用全注解的方式 package com.at

尚硅谷springboot学习13-配置的加载

配置可以有很多不同的来源,也有不同的加载顺序,下面来具体的看一下 配置文件加载位置 spring boot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件 –file:./config/ –file:./ –classpath:/config/ –classpath:/ –以上是按照优先级从高到低的顺序,所有位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置内容. 上面四个位置在一个项目中是这样

尚硅谷springboot学习20-web开发简介

使用SpringBoot 1).创建SpringBoot应用,添加我们需要的模块: 2).SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来 3).自己编写业务代码: 深入理解自动配置原理 这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?xxx xxxxAutoConfiguration:帮我们给容器中自动配置组件: xxxxProperties:配置类来封装配置文件的内容: 原文地址:https://www.cnb