SpringMvc初始化ViewResolver(九)


github原文链接 https://github.com/DespairYoke/java-advance。创作不易,请给个免费的star,已表支持。

ViewResolver

ViewResolver的作用

public interface ViewResolver {
    @Nullable
    View resolveViewName(String viewName, Locale locale) throws Exception;

}

viewResovler只有一个方法resolveViewName,由参数观察,可以得知,是对返回后的视图名称,和使用本地环境进行处理。下面引入使用示例供参考.

示例

@GetMapping(value = "hello")
public String index(String name) {
    return "index";
}

其中index就是参数中的viewName。

onRefresh初始化

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);
}

initViewResolversinitStrategies方法中被调用。

private void initViewResolvers(ApplicationContext context) {
    this.viewResolvers = null;
    //加载app-context.xml中配置的viewResolver
    if (this.detectAllViewResolvers) {
        // Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
        Map matchingBeans =
                BeanFactoryUtils.beansOfTypeIncludingAncestors(context, MyViewResolver.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.viewResolvers = new ArrayList<>(matchingBeans.values());
            // We keep ViewResolvers in sorted order.
         AnnotationAwareOrderComparator.sort(this.viewResolvers);
        }
    }
    //如果没有配置的viewResolver使用配置文件默认配置
    if (this.viewResolvers == null) {
        this.viewResolvers = getDefaultStrategies(context, MyViewResolver.class);
    }
}

该方法大致是先从bean工厂中拿我们的视图,也就是我们在app-context.xml配置的视图解析器,如果没有找到则调用DispatcherServlet.properties中配置的viewResolver。


    
    

我这里配置了viewResolver,所以会从bean工厂中拿到这个class。

你可能感兴趣的:(SpringMvc初始化ViewResolver(九))