十七、SpringBoot MVC配置原理

狂神说Java:https://www.bilibili.com/video/BV1PE411i7CV

官网:https://docs.spring.io/spring-boot/docs/2.4.0/reference/html/spring-boot-features.html#boot-features-developing-web-applications在这里插入图片描述

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.

1、结合官方文档学习源码

(1)WebMvcConfigurer是一个接口,配置类实现该接口
WebMvcAutoConfiguration类的静态内部类WebMvcAutoConfigurationAdapter在这里插入图片描述
WebMvcConfigurer接口在这里插入图片描述

(2)查看视图解析器类ContentNegotiatingViewResolver
在这里插入图片描述
发现其实现了ViewResolver接口。于是我们可以自定义视图解析器。实现了视图解析器接口的类。就可以看作视图解析器。

(3)查看视图解析器接口ViewResolver源码
在这里插入图片描述

需要实现这个方法。

2、自定义配置类

MyMvcConfig.java

package com.kuang.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;

/**
 * @Description TODO
 * 扩展MVC DispatcherServlet
 * 如果你想diy一些定制化的功能。只要写这个组件。然后将它交给SpringBoot,
 * SpringBoot就会帮我们自动装配
 * @Author Administrator
 * @Date 2020/12/10 13:43
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Bean
    ViewResolver myViewResolver(){
        return new MyViewResolver();
    }

    /**
     * public interface ViewResolver 实现了视图解析器接口的类。就可以看作视图解析器
     * 自定义视图解析器
     */
    public static class MyViewResolver implements ViewResolver {

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

}

3、断点调试

在SpringMVC的学习中,我们知道Spring的web框架围绕DispatcherServlet设计。DispatcherServlet的作用是将请求分发到不同的处理器。因此可以在DispatcherServlet入口处打断点,查看程序运行情况。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值