spring源码学习(八)容器功能拓展
程序员文章站
2022-05-21 19:21:26
...
我们在项目上常用的一般是ClassPathXmlApplicationContext这个类.
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
public void setConfigLocations(@Nullable 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;
}
}
@Override
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,进行Xml文件获取
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//对BeanFactory进行各种功能填充
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//子类覆盖方法做额外处理
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//**各种BeanFactory处理器
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注册拦截Bean创建的Bean处理器,这里只是注册,真正的调用在getBean
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//为上下文初始化Message源,即国际化
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中查找Listener bran
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//初始化剩下的单实例
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//完成刷新过程,通知生命周期处理器lifecycleProcessor刷新
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();
}
}
}
在ClassPathXmlApplicationContext中,做了很多功能上的拓展,增加了spel语言支持,增加了属性注册编辑器,添加了ApplicationContext AwreProcessor处理器,设置依赖忽略和注册依赖,BeanFactory的后处理等,但是核心的东西依然和XmlBeanFactory中相同,所以就不在深入查看源代码了,之后会看一下spring AOP的源码,以后有时间的话会在重新把这里的源码补全。
上一篇: 二叉树的二叉链表的简单实现及操作
下一篇: Spring 延迟初始化