上一篇部落格 springMVC源碼分析--ViewResolver視圖解析器(一)中我們介紹了一些springMVC提供的很多視圖解析器ViewResolver,在開發的一套springMVC系統中是可以使用多個視圖的,當然就需要配置多個視圖解析器了,ViewResolverComposite簡單來說就是使用簡單的List來儲存你配置使用的視圖解析器。
ViewResolverComposite中定義了兩個變量:
(1)private final List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>();用來存儲所有的視圖解析器
(2)private int order 用來配置視圖解析器的使用順序。
public class ViewResolverComposite implements ViewResolver, Ordered, InitializingBean,
ApplicationContextAware, ServletContextAware {
//用來存儲所有的視圖解析器
private final List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>();
//設定視圖解析器的執行順序
private int order = Ordered.LOWEST_PRECEDENCE;
//設定視圖解析器
public void setViewResolvers(List<ViewResolver> viewResolvers) {
this.viewResolvers.clear();
if (!CollectionUtils.isEmpty(viewResolvers)) {
this.viewResolvers.addAll(viewResolvers);
}
}
//擷取所有的視圖解析器
public List<ViewResolver> getViewResolvers() {
return Collections.unmodifiableList(this.viewResolvers);
}
//設定執行順序
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
for (ViewResolver viewResolver : this.viewResolvers) {
if (viewResolver instanceof ApplicationContextAware) {
((ApplicationContextAware)viewResolver).setApplicationContext(applicationContext);
}
}
}
@Override
public void setServletContext(ServletContext servletContext) {
for (ViewResolver viewResolver : this.viewResolvers) {
if (viewResolver instanceof ServletContextAware) {
((ServletContextAware)viewResolver).setServletContext(servletContext);
}
}
}
//初始化視圖解析器
@Override
public void afterPropertiesSet() throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
if (viewResolver instanceof InitializingBean) {
((InitializingBean) viewResolver).afterPropertiesSet();
}
}
}
//生成View對象
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, locale);
if (view != null) {
return view;
}
}
return null;
}
}