ApplicationContext和BeanFactory两者都是用于加载Bean的,但是相比之下,ApplicationContext提供了更多的扩展功能。
1.initPropertySources留给子类重写,可以初始化PropertySource
2.validateRequiredProperties则是对属性进行验证
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
// 定制BeanFactory
customizeBeanFactory(beanFactory);
// 加载beandefinition
loadBeanDefinitions(beanFactory);
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
1.设置是否允许覆盖同名称不同定义的对象
2.提供了注解@Qualifier和@Autowired的支持
1.将beandefinition加载入beanfactory中
1.为beanFactory设置BeanExpressionResolver,这个解析器何时用到呢?在bean进行属性填充的applyPropertyValues会用到, evaluateBeanDefinitinoString
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
在注入时,有时候需要注入Date,File。而配置是String,这时候就需要用到属性注册编辑器了。此处Spring加了一些内置的属性注册编辑器。
之前我们已经提到过,BeanPostProcessor会在bean填充完属性后被调用。 看一下这个BeanPostProcessor源码就知道,它是在调用aware接口的bean。
忽略掉Aware的依赖注入
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
通过上面的注册后,当你的类需要BeanFactory.class时,自然会能够给你注入
会调用BeanFactoryPostProcessor的postProcessBeanFactory方法
即遍历调用getBean
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// 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);
}
初始化LifecycleProcessor
启动所有实现了Lifecycle接口的bean
发布ContextRefreshedEvent事件