若是須要使運行速度更快,在建立一個spring的ioc工廠時每每會使用ApplicationContext而不是BeanFactory :spring
ApplicationContext ioc = new ClassPathXmlApplicationContext("config/applicationContext.xml");數組
在讀了其在spring的開源代碼後在此總結一下個人收穫。app
其中ApplicationContext是一個接口,它繼承了EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,MessageSource, ApplicationEventPublisher, ResourcePatternResolver等接口:this
它定義的方法有:xml
Stirng getId(); //得到application context特有的Id,若是沒有的話會返回null對象
String getApplicationName(); //得到當前context所屬的應用的名字繼承
String getDisplayName(); //得到context默認的名稱接口
long getStartupDate(); //當context第一次被加載時得到時間戳element
ApplicationContext getParent(); //返回applicationContext的父類,有層次關係get
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
在New一個容器時此處調用的方法源代碼爲:
/**
*建立一個新的ClassPathXmlApplicationContext,從被給與的xml文件加載定義好的對象,並刷新context
*/
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
其中this調用自身的方法:
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent); //其中super()方法根據參數ApplicationContext parent從被給予的父類的context建立一個新的AbstractXmlApplicationContext
setConfigLocations(configLocations);
if (refresh) {
refresh(); //更新已有的單例模式
}
}
其中 setConfigLocations()來自抽象類AbstractRefreshableConfigApplicationContext中的方法:
/**
*爲application context 配置路徑(config locations)
*/
public void setConfigLocations(String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
/**
*public static void noNullElements(Object[] array, String message) {
* if (array != null) {
* for (Object element : array) {
* if (element == null) {
* throw new IllegalArgumentException(message); //若是array不爲null,遍歷array[]數組中的元素,若是存在元素爲null,則拋出異常,異常信息爲參數message
* }
* }
* }
* }
*/
this.configLocations = new String[locations.length]; //AbstractRefreshableConfigApplicationContext 存在的(private String[] configLocations) 一個String數組,此處根據參數地址location的長度來設置configLocations
for (int i = 0; i < locations.length; i++) { this.configLocations[i] = resolvePath(locations[i]).trim(); //將原有的路徑進行替換成所傳入的location參數 } } else { this.configLocations = null; } }