模式:
1)springboot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)。如果有就用用户配置的,如果没有,才自动配置。如果有些组件可以有多个(如ViewResolver),则将用户配置的和自己默认的组合起来。
2)在springboot中会有非常多的Configurer帮助我们进行扩展配置
================================================================================================
1、
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration
class of type WebMvcConfigurer
but without @EnableWebMvc
. If you wish to provide custom instances of RequestMappingHandlerMapping
, RequestMappingHandlerAdapter
, or ExceptionHandlerExceptionResolver
, you can declare a WebMvcRegistrationsAdapter
instance to provide such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration
annotated with @EnableWebMvc
.
编写一个配置类@Configuration,是WebMvcConfigurer
类型,不能标注@EnableWebMvc
.
既保留了所有的自动配置,也能使用我们的扩展的配置。
原理:
1)WebMvcAutoConfiguration是springmvc的自动配置类
2)在做其他自动配置时会导入@Import(EnableWebMvcConfiguration.class)
3)容器中所有的WebMvcConfigurer都会一起起作用
4)我们的配置类也会被调用
效果:springmvc的自动配置和我们的扩展配置都会起作用
例如:
新建config包MyMvcConfig类
package com.cnstrong.springboot04webrestfulcrud.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//使用WebMvcConfigurer可以扩展springmvc功能
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//设置视图映射规则,把什么请求映射到什么页面
registry.addViewController("/student").setViewName("success");
}
}
================
自动装配一旦标注在了方法上,那么参数就要从容器中获取。
//一个参考实现:将所有的WebMvcConfigurer相关配置都来一起调用
2、全面接管springmvc
springboot对springmvc的自动配置不需要了,所有都是我们自己配。所有的springmvc的自动配置都失效了。
我们需要在配置类中添加@EnableWebMvc即可
原理:为什么加上@EnableWebMvc后自动配置就失效了
@EnableWebMvc将WebMvcConfigurationSupport组件导入进来,导入的WebMvcConfigurationSupport只是springmvc最基本的功能。viewcontroller、拦截器等需要自己再来配置。
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Import(DelegatingWebMvcConfiguration.class) public @interface EnableWebMvc { }
@Configuration public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
@Configuration @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class }) //容器中没有这个组件的时候,这个自动配置类才生效 @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10) @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class }) public class WebMvcAutoConfiguration {