私たちは皆、完全なトランク春のApplicationContextのと同等ながら、春たBeanFactoryのコアは、心と等価であることを私たちからソースコードを知っています:
BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationcontext.xml"));
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
ApplicationContextのは、MessageSource(ニュース)は、ApplicationEventPublisher(イベント)を一元管理など、本当に胴体の完全なカウントでたBeanFactoryは、ResourceLoaderは、リソース管理と負荷のクラスを提供して継承するだけでなく、EnvironmentCapable(環境)を継承しました。
ApplicationContextのたBeanFactoryと比較すると、機能の多くを延長してApplicationContextたBeanFactoryは、すべての機能が含まれているように、ApplicationContextのは、たBeanFactoryを継承しています。
ApplicationContextのAC =新ClassPathXmlApplicationContext( "applicationContext.xmlを");
使用ClassPathXmlApplicationContextは、コンフィギュレーションXMLファイルをロードapplicationContext.xmlを
我々はClassPathXmlApplicationContext出所を追跡:
ここでは文字列configLocationはapplicationContext.xmlをプロファイルパスであるのです。
ここでは、パラメータを覚えている:configLocationはapplicationContext.xmlをされ、リフレッシュがtrueで、親はnullです。
1、スーパー(親)親クラスのコンストラクタを呼び出すにはAbstractApplicationContext resourcePatternResolverに初期化されます。
这里一直跟踪super(parent)到底:
那么好了,这里的parent是null;就直接可以看出来AbstractApplicationContext中设置父类的参数parent为null,setParent(null);初始化了this();也就初始化了resourcePatternResolver。
2、setConfigLocations(configLocations)解析spring的配置文件地址,设置到configLocations。
这里的configLocations就是配置文件的路径。
3、refresh()这是ApplicationContext初始化的核心,会在这里初始化BeanFactory,解析XML加载BeanDefinition,注册bean处理器,注册事件添加监听等。
这里if判断refresh为true。
这里的refresh源码太多了,我就把源码复制下来:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 刷新上下文环境
prepareRefresh();
// 初始化BeanFactory,进行xml文件读取,这里是重点
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 对BeanFactory进行各种功能的填充
prepareBeanFactory(beanFactory);
try {
// 子类覆盖方法做其他的处理
postProcessBeanFactory(beanFactory);
// 激活BeanFactory的处理器
invokeBeanFactoryPostProcessors(beanFactory);
// 注册拦截Bean创建的Bean处理器
registerBeanPostProcessors(beanFactory);
// 为上下文初始化Message源
initMessageSource();
// 初始化应用消息广播器
initApplicationEventMulticaster();
// 留给子类初始化其他的bean
onRefresh();
// 查找Listeners bean,注册到消息广播器中
registerListeners();
// 初始化剩下的单实例
finishBeanFactoryInitialization(beanFactory);
// 完成刷新过程,通知生命周期处理器
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
查看ConfigurableListableBeanFactory可以看到XmlBeanFactory,这里我们就可以知道初始化了
BeanFactory。