標籤:style blog http color os io 使用 strong ar
1.在ApplicationContext容器中,我們以常用的FileSystemXmlApplicationContext的實現為例來說明ApplicationContext容器的設計原理。
2.在FileSystemXmlApplicationContext的設計中,我們看到ApplicationContext應用內容相關的主要功能已經在FileSystemXmlApplicationContext的基類AbstractXmlApplication中實現了,在FileSystemXmlApplicationContext中,作為一個具體的應用上下文,只需要實現和它自身設計相關的兩個功能。
3.一個功能是,如果應用直接使用FileSystemXmlApplicationContext,對於執行個體化這個應用上下文的支援,同時啟動IoC容器的refresh()過程。這在FileSystemXmlApplicationContext的代碼實現中可以看到,代碼如下:
1 /** 2 * Create a new FileSystemXmlApplicationContext with the given parent, 3 * loading the definitions from the given XML files. 4 * @param configLocations array of file paths 5 * @param refresh whether to automatically refresh the context, 6 * loading all bean definitions and creating all singletons. 7 * Alternatively, call refresh manually after further configuring the context. 8 * @param parent the parent context 9 * @throws BeansException if context creation failed10 * @see #refresh()11 */12 public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)13 throws BeansException {14 15 super(parent);16 setConfigLocations(configLocations);17 if (refresh) {18 refresh();19 }20 }FileSystemXmlApplicationContext(String[] configLocations,boolean,ApplicationContext)
4.這個refresh()過程會牽涉IoC容器啟動的一系列複雜操作,同時,對於不同的容器實現,這些操作都是類似的,因此在基類中將它們封裝好。所以,我們在FileSystemXmlApplicationContext的設計中看到的只是一個簡單的調用。
5.另一功能是與FileSystemXmlApplicationContext設計具體相關的功能,這部分與怎樣從檔案系統中載入XML的Bean定義資源有關。
6.通過這個實現,可以在檔案系統中讀取以XML形式存在的BeanDefinition做準備,因為不同的應用上下文實現對應著不同的讀取BeanDefinition的方式,在FileSystemXmlApplicationContext中的實現代碼如下:
1 /** 2 * Create a new FileSystemXmlApplicationContext with the given parent, 3 * loading the definitions from the given XML files. 4 * @param configLocations array of file paths 5 * @param refresh whether to automatically refresh the context, 6 * loading all bean definitions and creating all singletons. 7 * Alternatively, call refresh manually after further configuring the context. 8 * @param parent the parent context 9 * @throws BeansException if context creation failed10 * @see #refresh()11 */12 public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)13 throws BeansException {14 15 super(parent);16 setConfigLocations(configLocations);17 if (refresh) {18 refresh();19 }20 }getResourceByPath
可以看到,調用這個方法,可以得到FileSystemResource的資源定位。
ApplicationContext容器的設計原理