1 SpringBoot 支持的一些特性
- 包含 ContentNegotiatingViewResolver 和 BeanNameViewResolver bean。
- 支持服务静态资源,包括对 webjar 的支持(在本文后面介绍)。
- 转换器、 GenericConverter 和 Formatter bean 的自动注册。
- MessageCodesResolver 的自动注册(在本文后面介绍)。
- 自动使用 ConfigurableWebBindingInitializer bean
2 如果您希望保留 Spring Boot MVC 定制并进行更多的 MVC 定制,可以添加您自己的 WebMvcConfigurer类型的@configuration 类,但不要添加@Enablewebmvc。
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
}
查看WebMvcAutoConfiguration
// 当WebMvcConfigurationSupport 类不存在时,自动配置才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
}
查看@EnableWebMvc注解
@Target(ElementType.TYPE)
@Documented
//导入了DelegatingWebMvcConfiguration 类
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
继续查看DelegatingWebMvcConfiguration 类
@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
因此@EnableWebMvc 实际上导入了WebMvcConfigurationSupport 的类,因此会导致SpringBoot ,WebMvcAutoConfiguration 自动配置失效
1 下面自定义扩展SpringBoot MVC类 视图解析器
1 查看WebMvcAutoConfiguration 中的ViewResovler
@Bean
@ConditionalOnBean(View.class)
@ConditionalOnMissingBean
public BeanNameViewResolver beanNameViewResolver() {
BeanNameViewResolver resolver = new BeanNameViewResolver();
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return resolver;
}
@Bean
@ConditionalOnBean(ViewResolver.class)
@ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class)
public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class));
// ContentNegotiatingViewResolver uses all the other view resolvers to locate
// a view so it should have a high precedence
resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
return resolver;
}
发现共同特点
- 在WebMvcConfigurer类型下的@Configuration ,扩展SpringBoot MVC
- 自定义相关功能的类
- 在 @Configuration ,注册 @Bean
1 首先编写一个WebMvcConfigurer类型的配置类
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
}
2 编写一个实现某个功能扩展的类
public class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
3 在MyWebMvcConfigurer ,注册 @Bean
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Bean
public ViewResolver getViewResolver(){
return new MyViewResolver();
}
}
4 在DispatcherServlet中的doDispatch方法,断点调式
可以看到自定义视图解析成功