1. 程式人生 > >springMVC原始碼解析--ViewResolverComposite檢視解析器集合(二)

springMVC原始碼解析--ViewResolverComposite檢視解析器集合(二)

上一篇部落格 springMVC原始碼分析--ViewResolver檢視解析器(一)中我們介紹了一些springMVC提供的很多檢視解析器ViewResolver,在開發的一套springMVC系統中是可以使用多個檢視的,當然就需要配置多個檢視解析器了,ViewResolverComposite簡單來說就是使用簡單的List來儲存你配置使用的檢視解析器。

ViewResolverComposite中定義了兩個變數:

(1)private final List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>();用來儲存所有的檢視解析器

(2)private int order 用來配置檢視解析器的使用順序。

ViewResolverComposite的原始碼如下,其沒有多少具體的功能,主要就是一個檢視解析器集合。

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

}