文章目录
- refresh方法源码
- prepareRefresh实现
- obtainFreshBeanFactory实现
- refreshBeanFactory方法实现
- prepareBeanFactory方法实现
- invokeBeanFactoryPostProcessors方法实现
- registerBeanPostProcessors方法实现
- initMessageSource方法实现
- initApplicationEventMulticaster方法实现
- registerListeners方法实现
- finishBeanFactoryInitialization方法实现
- finishRefresh方法实现
- destroyBeans方法实现
以下面测试代码为例:
public class BaseTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
TestBean testBean = context.getBean("testBean", TestBean.class);
testBean.echo();
}
}
运行后,首先调用ClassPathXmlApplicationContext构造函数
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
具体调用以下构造方法:
// configLocations = new String[] {configLocation}
// refresh = true,表示要刷新初始化容器
// parent = null,表示不存在父容器
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
// 通过层层调用父构造函数,主要初始化了this.resourcePatternResolver=new PathMatchingResourcePatternResolver(this);后续可以通过适配符寻找符合条件的java类
super(parent);
// 遍历解析传入的配置文件路径,将路径中的占位符替换成相关的环境变量。
setConfigLocations(configLocations);
if (refresh) { // true
// 调用父类AbstractApplicationContext中定义的refresh方法,完成Spring容器和应用上下文的创建工作。
refresh();
}
}
refresh方法源码
具体refresh代码如下:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 供子类拓展,添加创建前必需属性,校验如果必需属性不存在则抛出MissingRequiredPropertiesException异常
prepareRefresh();
// 调用子类实现方法获取(创建或刷新)BeanFacotry容器,对于ClassPathXmlApplicationContext,主要调用了AbstractRefreshableApplicationContext中实现的方法
// 在这里,将xml配置文件中 的Bean解析成了一个个BeanDefinition,建立一个beanName-> beanDefinition 的 map
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 设定类加载器,spel解析器,属性编辑解析器等,忽略特定接口的依赖注册(在特定时刻相关Bean再完成注入),注册一些系统Bean供依赖注入使用。
prepareBeanFactory(beanFactory);
try {
// BeanFactory创建完的后置处理。当前为空实现,供子类拓展
postProcessBeanFactory(beanFactory);
// 调用BeanFacotry的相关后置处理器,如果实现了Order相关接口,会先进行排序。
invokeBeanFactoryPostProcessors(beanFactory);
// 注册相关BeanPostProcessor,供Bean生成前后调用。
registerBeanPostProcessors(beanFactory);
// 初始化国际化信息源
initMessageSource();
// 初始化Spring相关上下文时间广播器
initApplicationEventMulticaster();
// 模版方法供子类实现,用于初始化一些特殊Bean配置等
onRefresh();
// 注册实现了ApplicationListener接口的事件监听器,用于后续广播器广播事件
registerListeners();
// BeanFactory初始化完成时调用,初始ConversionService Bean,冻结beanFactory配置,并开始创建BeanFactory中所有非懒加载的单例Bean
finishBeanFactoryInitialization(beanFactory);
// 初始化Lifecycle处理器,调用onRefresh方法,广播ContextRefreshedEvent。
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;
}
}
}
prepareRefresh实现
下面先粗略讲解refresh函数下每一步操作的源码实现:
// 供子类拓展,添加创建前必需属性,校验如果必需属性不存在则抛出MissingRequiredPropertiesException异常
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
synchronized (this.activeMonitor) {
this.active = true;
}
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
// 内部是一个空实现,主要供子类拓展自己ApplicationContext,设置必需的属性
initPropertySources();
// 校验必需的属性是否存在,具体参考下面的代码
getEnvironment().validateRequiredProperties();
}
public void validateRequiredProperties() {
MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException();
for (String key : this.requiredProperties) {
// 如果存在属性缺失,记录下来
if (this.getProperty(key) == null) {
ex.addMissingRequiredProperty(key);
}
}
// 存在缺失属性则抛出异常
if (!ex.getMissingRequiredProperties().isEmpty()) {
throw ex;
}
}
obtainFreshBeanFactory实现
// 调用子类实现方法获取(创建或刷新)BeanFacotry容器,对于ClassPathXmlApplicationContext,主要调用了AbstractRefreshableApplicationContext中实现的方法
// 在这里,将xml配置文件中 的Bean解析成了一个个BeanDefinition,建立一个beanName-> beanDefinition 的 map
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 刷新初始化BeanFactory,核心在这一步
refreshBeanFactory();
// 获取上一步初始化的BeanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
refreshBeanFactory方法实现
具体实现位于AbstractRefreshableApplicationContext类下:
protected final void refreshBeanFactory() throws BeansException {
// 如果已经存在,先销毁存在的
if (hasBeanFactory()) {
// 销毁工厂的所有相关单例Bean
destroyBeans();
// 清理工厂相关配置
closeBeanFactory();
}
try {
// 通过new DefaultListableBeanFactory(getInternalParentBeanFactory())创建一个空工厂实例
// 其中getInternalParentBeanFactory()=null
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 记录映射id -> DefaultListableBeanFactory到一个静态Map
beanFactory.setSerializationId(getId());
// 定制Bean工厂,主要供用户自定义子类拓展是否允许BeanDefinition重写(默认true)、循环引用(默认true)等功能。
customizeBeanFactory(beanFactory);
// 读取xml配置,将配置中定义的Bean以BeanDefinition封装保存到beanFactory中。
loadBeanDefinitions(beanFactory);
// 记录引用。
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
prepareBeanFactory方法实现
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 设定类加载器,spel解析器,属性编辑解析器等 context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
//忽略特定接口的实现类依赖注入,在Spring特定初始实现了这些相关接口的Bean的特定时刻再统一完成注入,避免重复注入等问题。具体是在ApplicationContextAwareProcessor中完成
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// 设置了几个自动装配的特殊规则,如果是BeanFactory类型,则注入beanFactory对象,如果是ResourceLoader、ApplicationEventPublisher、ApplicationContext类型则注入当前对象(applicationContext对象)
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 判断是否定义了名为loadTimeWeaver的bean,如果定义了则添加loadTimeWeaver功能的beanPostProcessor扩展,并且创建一个临时的classLoader来让其处理真正的bean。spring的loadTimeWeaver主要是通过 instrumentation 的动态字节码增强在装载期注入依赖
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 注册环境相关的Bean到容器中,后续便支持这些Bean的依赖注入相关操作
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
invokeBeanFactoryPostProcessors方法实现
总体方法实现逻辑:调用所有注册在Spring容器中的实现BeanFactoryPostProcessors接口Bean的postProcessBeanFactory方法。如果这些BeanFactoryPostProcessor实现了Order接口,会先进行排序再依次调用。通过这些BeanFactoryPostProcessors,可以对BeanFacotry进一步定制,如修改里面的Bean属性等。
// 有两种方式添加具体的后置处理器。
// 一种是编程式添加:`context.addBeanFactoryPostProcessor`,这个通过getBeanFactoryPostProcessors获取
// 另一种是通过xml配置`<bean class="com.xx.XxxBeanFactoryPostProcessor" />`,这个通过beanFactory.getBeansOfType获取
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
Set<String> processedBeans = new HashSet<String>();
// 如果是BeanDefinitionRegistry的实现类,需要获取出来,调用其中的postProcessBeanDefinitionRegistry方法
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
new LinkedList<BeanDefinitionRegistryPostProcessor>();
for (BeanFactoryPostProcessor postProcessor : getBeanFactoryPostProcessors()) {
// 如果是BeanDefinitionRegistryPostProcessor的实例,还需要调用postProcessBeanDefinitionRegistry()方法
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryPostProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
registryPostProcessors.add(registryPostProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// 调用基于getBeansOfType(BeanDefinitionRegistryPostProcessor.class, true, false)获取的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry,注意这里根据实现Order接口进行优先级排序
Map<String, BeanDefinitionRegistryPostProcessor> beanMap = beanFactory.getBeansOfType(BeanDefinitionRegistryPostProcessor.class, true, false);
List<BeanDefinitionRegistryPostProcessor> registryPostProcessorBeans =
new ArrayList<BeanDefinitionRegistryPostProcessor>(beanMap.values());
OrderComparator.sort(registryPostProcessorBeans);
for (BeanDefinitionRegistryPostProcessor postProcessor : registryPostProcessorBeans) {
postProcessor.postProcessBeanDefinitionRegistry(registry);
}
// 调用上述方法的基于BeanFactoryPostProcessor接口的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(registryPostProcessorBeans, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
processedBeans.addAll(beanMap.keySet());
}
else {
// 仅调用通过编程注册的处理器方法
invokeBeanFactoryPostProcessors(getBeanFactoryPostProcessors(), beanFactory);
}
// 根据Type=BeanFactoryPostProcessor获取相关的后置处理器,由于BeanDefinitionRegistryPostProcessor属于
String[] postProcessorNames =BeanFactoryPostProcessor的子类,所以后面会过滤掉上面调用过的processedBeans
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// 区分实现了PriorityOrdered,Ordered等接口和未实现Order接口的后置处理器,依次排序后调用。
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
OrderComparator.sort(priorityOrderedPostProcessors);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
OrderComparator.sort(orderedPostProcessors);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
}
// 具体invokeBeanFactoryPostProcessors方法实现如下:
private void invokeBeanFactoryPostProcessors(Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
// 依次遍历调用其中的postProcessBeanFactory
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanFactory(beanFactory);
}
}
registerBeanPostProcessors方法实现
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 根据BeanPostProcessor类型获取容器中具体的BeanNames
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 区分实现了PriorityOrdered,Ordered等接口和未实现Order接口的后置处理器,依次排序后添加到ArrayList,最后调用时确保调用顺序。
// 如果是MergedBeanDefinitionPostProcessor的实例,会收集起来排序后再次重新注册,、
// MergedBeanDefinitionPostProcessor中定义了postProcessMergedBeanDefinition方法
//会在创建Bean实例后,填充Bean属性和调用其中所有后置处理器的postProcessBeforeInitialization前调用postProcessMergedBeanDefinition,
//用来提供机会修改MergedBeanDefinition
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
if (isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
OrderComparator.sort(priorityOrderedPostProcessors);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
OrderComparator.sort(orderedPostProcessors);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors.
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
OrderComparator.sort(internalPostProcessors);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// 添加ApplicationListenerDetector后置处理器,
// 在Bean初始化后检查是否实现了ApplicationListener接口,
// 是则加入当前的applicationContext的applicationListeners列表
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector());
}
// 其中registerBeanPostProcessors实现如下:
private void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
// 其中调用了addBeanPostProcessor方法:
// 其中我们看到,会先尝试移除再添加,避免出现重复的后置处理器,所以前面的internalPostProcessors都会再最后添加上去
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
this.beanPostProcessors.remove(beanPostProcessor);
this.beanPostProcessors.add(beanPostProcessor);
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
}
initMessageSource方法实现
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 如果包含messageSourceBean
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
// 调用getBean方法完成初始化
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isDebugEnabled()) {
logger.debug("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// 此处是委托模式的体现。如果没有配置此bean,那么初始化一个DelegatingMessageSource对象,此类是一个空实现,同样用以处理getMessage调用请求。
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
"': using default [" + this.messageSource + "]");
}
}
}
initApplicationEventMulticaster方法实现
// 如果beanFactory中包含applicationEventMulticaster实例或定义,则获取或初始化,如果不存在,初始化一个SimpleApplicationEventMulticaster用于进行Spring事件广播
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 存在
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isDebugEnabled()) {
logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
// 不存在
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
"': using default [" + this.applicationEventMulticaster + "]");
}
}
}
registerListeners方法实现
protected void registerListeners() {
// 将目前已经通过ApplicationListenerDetector或其他方式添加的ApplicationListener注册到广播器中。
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 根据getBeanNamesForType获取xml配置的事件监听器并注册到广播器中。
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
}
finishBeanFactoryInitialization方法实现
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 初始化并设置容器的conversionService实例
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// 提前初始化LoadTimeWeaverAware相关的Bean。方便进行相关的转换处理
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// 停止使用临时的类加载器
beanFactory.setTempClassLoader(null);
// 冻结配置
beanFactory.freezeConfiguration();
// 初始化所有非懒加载的单例对象
beanFactory.preInstantiateSingletons();
}
finishRefresh方法实现
protected void finishRefresh() {
// 初始化上下文LifecycleProcessor来拓展管理ApplicationContext的生命周期,会在ApplicatonContext刷新,关闭等时候触发LifecycleProcessor内部相应的函数
initLifecycleProcessor();
// 触发LifecycleProcessor的onRefresh操作
getLifecycleProcessor().onRefresh();
// 通过前面注册的时间广播器,广播ContextRefreshedEvent给所有注册了的ApplicationContextListener
publishEvent(new ContextRefreshedEvent(this));
// 在LiveBeansView添加当前初始化好的ApplicationContext
LiveBeansView.registerApplicationContext(this);
}
destroyBeans方法实现
// 销毁BeanFactory容器中所有的单例
protected void destroyBeans() {
getBeanFactory().destroySingletons();
}
// 具体实现如下,在DefaultSingletonBeanRegistry中
public void destroySingletons() {
if (logger.isInfoEnabled()) {
logger.info("Destroying singletons in " + this);
}
synchronized (this.singletonObjects) {
this.singletonsCurrentlyInDestruction = true;
}
String[] disposableBeanNames;
synchronized (this.disposableBeans) {
disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
}
// 对于实现了DisposableBean接口的Bean,一次调用内部的destroy方法
for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
destroySingleton(disposableBeanNames[i]);
}
// 清理相关上下文容器数据
this.containedBeanMap.clear();
this.dependentBeanMap.clear();
this.dependenciesForBeanMap.clear();
synchronized (this.singletonObjects) {
this.singletonObjects.clear();
this.singletonFactories.clear();
this.earlySingletonObjects.clear();
this.registeredSingletons.clear();
this.singletonsCurrentlyInDestruction = false;
}
}
public void destroySingleton(String beanName) {
// 从singletonObjects,singletonFactories,earlySingletonObjects,registeredSingletons等Map中移除相关引用
removeSingleton(beanName);
// 获取DisposableBean实例,准备调用内部的distroy方法
synchronized (this.disposableBeans) {
disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
}
destroyBean(beanName, disposableBean);
}
// 最后销毁方法如下:
protected void destroyBean(String beanName, DisposableBean bean) {
// 清除指定bean与创建这个bean所需要依赖的所有bean的依赖关系的缓存
Set<String> dependencies = this.dependentBeanMap.remove(beanName);
if (dependencies != null) {
if (logger.isDebugEnabled()) {
logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
}
for (String dependentBeanName : dependencies) {
// 递归销毁单例Bean
destroySingleton(dependentBeanName);
}
}
// 调用实现了DisposableBean接口的detory方法
if (bean != null) {
try {
bean.destroy();
}
catch (Throwable ex) {
logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex);
}
}
// 清除外部bean与被包含在外部bean的所有内部bean集合包含关系的缓存
Set<String> containedBeans = this.containedBeanMap.remove(beanName);
if (containedBeans != null) {
for (String containedBeanName : containedBeans) {
destroySingleton(containedBeanName);
}
}
// 清除指定bean与依赖指定bean的所有bean的依赖关系的缓存
synchronized (this.dependentBeanMap) {
for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Set<String>> entry = it.next();
Set<String> dependenciesToClean = entry.getValue();
dependenciesToClean.remove(beanName);
if (dependenciesToClean.isEmpty()) {
it.remove();
}
}
}
// 移除指定bean与创建这个bean所需要依赖的所有bean的依赖关系的缓存
this.dependenciesForBeanMap.remove(beanName);
}
至此,Spring初始化IOC容器的大致流程如上所示。中间还有一些核心流程,如xml文件的解析,Singleton、Prototype对象的创建、对象属性的依赖注入、一系列BeanPostProcessor及其相关子接口的调用时机等。在后续的文章中会一一进行介绍。