DispatcherServlet中有几个引用类型的属性,我们成为SpringMVC 9大组件
//多部件解析器:文件上传
@Nullable
private MultipartResolver multipartResolver;
//区域信息解析器:和国际化有关
@Nullable
private LocaleResolver localeResolver;
//主题解析器:强大的主题效果更换
@Nullable
private ThemeResolver themeResolver;
//handler映射信息:HandlerMappings
/** List of HandlerMappings used by this servlet. */
@Nullable
private List<HandlerMapping> handlerMappings;
//Handler的适配器
@Nullable
private List<HandlerAdapter> handlerAdapters;
//springmvc强大的异常解析功能:异常解析器
@Nullable
private List<HandlerExceptionResolver> handlerExceptionResolvers;
/** RequestToViewNameTranslator used by this servlet. */
//请求到视图名转换器:
@Nullable
private RequestToViewNameTranslator viewNameTranslator;
//springmvc中允许重定向性携带数据的功能
@Nullable
private FlashMapManager flashMapManager;
//视图解析器:
@Nullable
private List<ViewResolver> viewResolvers;
Springmvc在工作的时候,关键位置都是由这些组件完成的;
共同点:
- 全部都是接口:接口就是规范,提供了非常强大的扩展性;
1、九大组件的初始化
DispatcherServlst中九大组件初始化的地方:
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
初始化HandlerMapping
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
//detectAllHandlerMappings默认true,可以在web.xml中修改DispatcherServlet某些属性的默认值
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
else {
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}
// Ensure we have at least one HandlerMapping, by registering
// a default HandlerMapping if no other mappings are found.
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isTraceEnabled()) {
logger.trace("No HandlerMappings declared for servlet '" + getServletName() +
"': using default strategies from DispatcherServlet.properties");
}
}
}
组件的初始化:
- 去容器中找这个组件,如果没有找到,就用默认配置;
- 有些组件在容器中是使用类型找的;有些是使用id找的;