相比于BeanFactory接口,我們更多時候使用ApplicationContext接口來加載Bean,兩個接口都是來加載Bean的,相比之下ApplicationContext提供了更多擴充功能。使用ApplicationContext方式加載XML
ApplicationContext ctx = new ClassPathXmlApplicationContext("app.xml");
以ClassPathXmlApplicationContext.java為切入點
//其中configLocations為數組形式的xml形式的配置檔案路徑
public ClassPathXmlApplicationContext(String... configLocations) throws BeansException {
this(configLocations, true, null);
}
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
//todo 設定配置檔案路徑
setConfigLocations(configLocations);
if (refresh) {
//加載重新整理配置,可能是xml檔案也可能是其他屬性檔案
refresh();
}
}