在使用springboot,我们有时候可能会想把已经自动装配好的组件换成我们自己定义的。
对于如何替换,官网上是这样说的
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已经被装配好了。