ApplicationContext bf = new ClassPathXmlApplicationContext(“applicationContext.xml”);
1.首先调用构造器:
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
2.再调用构造器:
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
3.setConfigLocations(configLocations);方法:
public void setConfigLocations(String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
设置applicationContext.xml到configLocations数组中。
4.refresh()方法:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//为刷新做上下文的环境准备
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//初始化beanFactory,读取applicationContext.xml文件,使具有bean操作的所有功能
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//为beanFactory在上下文使用做准备,也就是扩展bean的功能,支持@autowired等注解
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//允许子类进行功能扩展的方法
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//在上下文中以bean的形式激活工厂处理器
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注册拦截bean创建的bean处理器
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//初始化信息资源
initMessageSource();
// Initialize event multicaster for this context.
//初始化事件广播
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//初始化特殊上下文子类找那个其他特殊的bean,用以子类功能扩展
onRefresh();
// Check for listener beans and register them.
//检查bean监听器并注册
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//初始化所有的剩下(非懒加载)的单例
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//发布通知事件
finishRefresh();
}
catch (BeansException ex) {
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;
}
}
}
总结refresh()方法中的主要功能:
1.为刷新做上下文的环境准备
2.初始化beanFactory,读取applicationContext.xml文件,使具有bean操作的所有功能
3.为beanFactory在上下文使用做准备,也就是扩展bean的功能,支持@autowired等注解
4.允许子类进行功能扩展的方法
5.在上下文中以bean的形式激活工厂处理器
6.注册拦截bean创建的bean处理器
7.初始化信息资源
8.初始化事件广播
9.初始化特殊上下文子类找那个其他特殊的bean,用以子类功能扩展
10.检查bean监听器并注册
11.初始化所有的剩下(非懒加载)的单例
12.发布通知事件