SpringBoot对Springmvc的自动配置以及如何扩展

Sping Boot 自动配置好了SpringMVC

13.1 SpringMVC的自动配置。

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

  1. Inclusion of ContentNegotiatingViewResolver and **BeanMameViewResolver **beans.
    自动配置了VIewResolver(视图解析器:根据方法的返回值得到视图对象View,视图对象决定如何渲染。转发?重定向?)
    ContentNegotiatingViewResolver :组合所有视图解析器的;
    如何自制视图解析器?我们可以给容器添加一个视图解析器;自动的将其组合进来。
@Configuration
public class MyConfig {

    //2.将我们的视图解析器添加到容器中去
    @Bean
    public ViewResolver myViewResolver() {
        return new MyViewResolver();
    }

    //1.实现ViewResolver接口,做我们自己的视图解析器
    public static class MyViewResolver implements ViewResolver {
        @Override
        public View resolveViewName(String viewName, Locale locale) throws Exception {
            return null;
        }
    }
}

image.png

  1. Support for serving static resources, including support for WebJars (see below). 静态资源文件夹路径,webjars
  2. Static index.html support. 静态首页访问。
  3. Custom Favicon support (see below). favicon.ico图标
  4. 自动注册了 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());//日期格式化组件
}

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

  1. Support for HttpMessageconverters (see below).
    • HttpMessageConverters : SpringMVC用来转换Http请求和响应的;User—Json ;
    • HttpMessageConverters是从容器中确定的;获取所有的HttpMessageConverter;
    • 自己给容器添加**HttpMessageConverter,只需要将自己的组件注册到容器中即可 **
  2. Automatic registration of MessageCodesResolver (see below).定义错误代码生成规则
  3. Automatic use of a ConfigurablewebBindingInitializer bean (see below).

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

初始化webDataBinder ; webDataBinder数据绑定器,将数据绑定到bean
请求数据=====JavaBean ;

org.springframework.boot.autoconfigure.web:web的所有自动配置场景。

13.2 如何修改SpringBoot的默认配置【重要!!!】

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

13.2 扩展Spring MVC【重要!!!】

保留Spring Boot MVC功能,并且只想添加额外的MVC配置(拦截器、格式化器、视图控制器等)
官网说明:
lf 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 ExceptionHandlerExXceptionResolver you can declare a weblvcRegistrationsAdapter instance providing such components.
lf you want to take complete control of Spring MVC, you can add your own Configuration annotated withEnablewebMvc .
翻译:
如果你想保留Spring Boot MVC功能,并且只想添加额外的MVC配置(拦截器、格式化器、视图控制器等),你可以添加自己的WebMvcConfigurerAdapter类型的@configuration类,但不需要@EnableWebMvc。如果您希望提供RequestMappingHandlerMapping、RequestMappingHandlerAdapter或ExceptionHandlerExXceptionResolver的自定义实例,则可以声明提供此类组件的webvcRegistrationsAdapter实例。
如果你想完全控制SpringMVC,你可以添加自己的带有EnablewebMvc注释的配置。
:::warning
编写一个配置类(@Configuration ),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc;【已过时!
:::

package com.example.myapplication.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //添加一个视图控制器
        //浏览器请求/abc 请求来到success,会被视图解析器解析
        //相当于
        //    @GetMapping("abc")
        //    public String abd(){
        //        return "success";
        //    }
        registry.addViewController("/abc").setViewName("success");
    }
}

image.png
不过这种方式已经过时!!!我们采用实现 WebMvcConfigurer 接口来实现。

package com.example.myapplication.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    //添加视图控制器
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/abc").setViewName("success");
    }
    
    //添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加我们的自定义拦截器
        registry.addInterceptor(new MyInterceptor());
    }
    //自定义我们的拦截器
    public static class MyInterceptor implements HandlerInterceptor{
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //业务逻辑处理
            String requestURI = request.getRequestURI();
            System.out.println(requestURI);
            //true-放过,false-拦截
            return true;
        }
    }


}

我们可以自定义的功能方法如下:
可以添加我们自己的视图控制器,拦截器,转换器等等。
image.png

原理︰
1 )WebMvcAutoConfiguration是SpringMVC的自动配置类
2 )在做其他自动配置时会导入;@lmport(EnableWebMvcConfiguration.class)
3 )容器中所有的WebMvcConfigurer都会一起起作用;
4 )我们的配置类也会被调用;
效果:SpringMVC的自动配置和我们的扩展配置都会起作用!

13.4 全面接管SpringMVC

SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配;
我们需要在配置类中添加@EnableWebMvc即可

package com.example.myapplication.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //添加一个视图控制器
        //浏览器请求/abc 请求来到success,会被视图解析器解析
        //相当于
        //    @GetMapping("abc")
        //    public String abd(){
        //        return "success";
        //    }
        registry.addViewController("/abc").setViewName("success");
    }
}

使用@EnableWebMvc后,原来Springboot对SpringMvc的自动配置失效!!!
也就是原来Springmvc被Springboot自动配置好的功能都会失效!!!
原理:
为什么@EnableWebMvc自动配置就失效了??
1 )@EnableWebMvc的核心

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

2)DelegatingWebMvcConfiguration
相当于@EnableWebMvc将WebMvcConfigurationSupport这个类导入进来了。

public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport{...}

3)WebMvcAutoConfiguration
image.png
@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;
导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值