SpringMVC九大组件
程序员文章站
2022-07-15 11:21:39
...
九大组件
在 DispatcherServlet 中存在很多属性,其中有九大组件:
/** 文件上传解析 */
private MultipartResolver multipartResolver;
/** 区域解析器:国际化 */
private LocaleResolver localeResolver;
/** 主题解析器 */
private ThemeResolver themeResolver;
/** 处理器的映射关系 */
private List<HandlerMapping> handlerMappings;
/** 处理器的适配器 */
private List<HandlerAdapter> handlerAdapters;
/** 处理器的异常解析器 */
private List<HandlerExceptionResolver> handlerExceptionResolvers;
/** 请求转视图名的转换器 */
private RequestToViewNameTranslator viewNameTranslator;
/** 支持重定向携带参数 */
private FlashMapManager flashMapManager;
/** 视图解析器 */
private List<ViewResolver> viewResolvers;
初始化
主要初始化逻辑在 DispatcherServlet.initStrategies() 方法中:
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
以 initHandlerMappings() 为例,其他方法类似:
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// 获从容器中获取所有的HandlerMapping
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,beanName=handlerMapping
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.
}
}
// 如果容器中没有HandlerMapping, 加载默认的
if (this.handlerMappings == null) {
// 获取默认的HandlerMapping,根据配置文件DispatcherServlet.properties
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isTraceEnabled()) {
logger.trace("No HandlerMappings declared for servlet '" + getServletName() +
"': using default strategies from DispatcherServlet.properties");
}
}
for (HandlerMapping mapping : this.handlerMappings) {
if (mapping.usesPathPatterns()) {
this.parseRequestPath = true;
break;
}
}
}
总结:先从容器中获取需要的组件,如果容器中没有,再根据配置文件加载默认的组件。