上集我们说到spring bean的注入方式如下:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student1 = (Student) context.getBean("student_zhangsan");
为什么创建一个context容器,就能从容器中获取bean实例?ClassPathXmlApplicationContext构造器中究竟实现了什么?
要了解spring内部实现,我们第一步先了解跟类有关的对象依赖关系。
从上图看出AbstractApplicationContext,AbstractRefreshableApplicationContext,AbstractRefreshableConfigApplicationContext
AbstractXmlApplicationContext,ClassPathXmlApplicationContext这几个类有具体 实现,其余的都是接口,从上图可以看出其核心 就是BeanFactory。
【ClassPathXmlApplicationContext构造器】
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
第一、ClassPathXmlApplicationContext构造器最终会调用到父类AbstractApplicationContext的构造方法
【AbstractApplicationContext构造器】
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader) {
Assert.notNull(resourceLoader, "ResourceLoader must not be null");
this.resourceLoader = resourceLoader;
}
从具体的源码中我们看到AbstractApplicationContext构造器初始化了一个ResourceLoader ,并初始化父类的ApplicationContext,具体什么作用后边再看
第二、加载XML的配置路径
第三、也就是其核心,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.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
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();
}
}
}
1.prepareRefresh()
——设置启动时间,是否激活标识位,初始化属性源(property source)配置
2.ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
——创建beanFactory,初始化了一个XmlBeanDefinitionReader并且loadBeanDefinitions,将所有的bean注入到beanFactory中
3.prepareBeanFactory(beanFactory)
——准备创建好的beanFactory(给beanFactory设置ClassLoader,设置SpEL表达式解析器,设置类型转化器(能将xml String类型转成相应对象),增加内置ApplicationContextAwareProcessor对象,忽略各种Aware对象,注册各种内置的对账对象(BeanFactory,ApplicationContext)等,注册AOP相关的一些东西,注册环境相关的一些bean
4.invokeBeanFactoryPostProcessors(beanFactory)
——扩展了BeanFactoryPostProcessor,现在这个境界看不懂
5.registerBeanPostProcessors(beanFactory)
——实例化和注册beanFactory中扩展了BeanPostProcessor的bean
6.initMessageSource()
——给BeanFactory注册单实例messageSource
7.initApplicationEventMulticaster()
——给BeanFactory注册消息广播类,默认注册applicationEventMulticaster
8.registerListeners()
——给applicationEventMulticaster注册监听者,bean实例名称,并进行广播applicationEventMulticaster
9.finishBeanFactoryInitialization(beanFactory)
——给BeanFactory设置conversionService(不知道干嘛的),初始化LoadTimeWeaverAware类型的bean实例,清除ClassLoader,初始化所有类对象(除了懒加载的类)
10.finishRefresh()
——给BeanFactory注册生命周期相关的Processor(默认DefaultLifecycleProcessor),调用了SmartLifecycle的start方法(作用?),进行广播ContextRefreshedEvent事件,向MBeanSevice注册LiveBeansView
protected void finishRefresh() {
// Initialize lifecycle processor for this context.
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
以上是源代码的大概步骤,认识水平有限,后续补齐、、、、、、、