springboot配置扩展

在使用springboot,我们有时候可能会想把已经自动装配好的组件换成我们自己定义的。

对于如何替换,官网上是这样说的

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features

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.

意思是如果要保留原有的Spring Boot MVC组件的配置同时定制属于自己的MVC配置(拦截器,格式化程序,视图控制器和其他功能),则可以添加自己@Configuration的type类,WebMvcConfigurer但不添加 @EnableWebMvc

package com.example.demo.config;

import com.example.demo.component.MyLocalResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
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 org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.Locale;

//diy一些功能,只要写一些组件,然后交给springboot,它就会自动装配
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @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;
    }
}
}

这样当我们在运行的时候,springboot就会帮我们自动装配了。
由于在运行的时候,一定会经过DispatcherServlet类,所以我们在其中的doDispatch方法打断点调试,
在这里插入图片描述
我们可以很清楚的看到我们的ViewResolver已经被装配好了。

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值