先定义一个mvc的简单的配置类,定义一下视图解析:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.dongsq")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp");
}
}
看一下@EnableWebMvc是怎么开启mvc功能的:
DelegatingWebMvcConfiguration中会对setConfigurers方法进行注入,会将我们自定义的WebMvcConfig类加入下图中的configurers集合:
DelegatingWebMvcConfiguration 继承了WebMvcConfigurationSupport,
我们定义了视图解析,先看WebMvcConfigurationSupport中的mvcViewResolver方法:
这里会调用到其子类DelegatingWebMvcConfiguration 中的configureViewResolvers方法:
这样就加载到了我们自己的配置,除了视图解析,拦截器、消息转换器、本地资源映射等等同样是这样配置,原理都是同样的一个调用流程。
在WebMvcConfigurationSupport中除了以上的配置,还会创建handlerMapping和handlerAdapter,例如RequestMappingHandlerMapping和RequestMappingHandlerAdapter,handlerMapping和handlerAdapter的作用这里不做赘述了。