11 spring-boot的MVC配置原理

11.1 spring-boot为MVC提供的自动配置

        1.ContentNegotiatingViewResolver视图解析器;

        2.静态资源或者支持WebJars;

        3.自动注册类型转换器:比如说前台提交user的字段,后台自动封装的意思;

        4.HttpMessageConverters:转换http的请求和相应,比如把一个user字符串转为一个json字符串;

        5.MessageCodesResolver:定义错误消息;

        6.index.html :支持首页映射;

        7.Favicon:支持图标映射;

        8.ConfigurableWebBindingInitializer:支持数据web的初始化绑定,把请求和数据封装到javaBean中;

11.2 扩展配置原理(理解)

        先创建一个包,叫做config,自定义的配置都放在里面;

        然后,再创建一个类叫MyMvcConfig的配置类,加上@Configuration注解,用这个类来全面扩展springMVC的配置;这个类必须实现WebMvcConfigurer接口,实现里面的方法即可;

        首先,要去实现视图解析器,搜索ContentNegotiatingViewResolver这个类,发现这个类实现了ViewResolver接口,因此这个类就是一个视图解析器;

public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport implements ViewResolver, Ordered, InitializingBean

        自己在内部写一个静态内部类:

package jiang.com.springbootstudy.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    // 放接口这样写,把bean放到接口里
    @Bean
    public ViewResolver myViewResolver(){
        return new MyViewResolver();
    }

    // 自定义了一个试图解析器
    public static class MyViewResolver implements ViewResolver{
        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
}

         所有请求(包括视图解析器)会经过DispatcherServlet,里面有个方法是doDispatcher,所有的请求和相应都会经过这,因此,打个断点。

         点击DeBug,刷新页面。然后会自动跳到断点这,控制台内容如下:

        打开this, 找到viewResolver点开,发现刚刚创建的视图解析器已经被加载进来了,并且经过了doDispatcher方法。

12.3 总结

        在springboot中,有非常多的xxxx Configuration帮助我们进行扩展配置,只要看见了这个东西,我们就要注意了!

        

        

猜你喜欢

转载自blog.csdn.net/no996yes885/article/details/131880226
今日推荐