深入剖析springioc容器的创建过程

@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// 放入容器环境上下文中一些信息主要是 active设置为true、closed设置为false、注入properties中的信息.
		prepareRefresh();

		// 告诉子类获取内部bean工厂(ConfigurableListableBeanFactory )
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// 将容器环境上下文中的信息注册到factory中
		prepareBeanFactory(beanFactory);

		try {
			// 允许在上下文子类中对bean工厂进行后处理。
			postProcessBeanFactory(beanFactory);

			// 调用在上下文中注册为bean的工厂处理器
			invokeBeanFactoryPostProcessors(beanFactory);

			// 注册拦截bean创建的bean处理器。
			registerBeanPostProcessors(beanFactory);

			// 初始化messageSource
			initMessageSource();

			// 为此上下文初始化事件Multicaster
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			onRefresh();

			// 将监听事件添加到Multicaster
			registerListeners();

			// 初始化beanfactory (non-lazy-init) singletons.
			finishBeanFactoryInitialization(beanFactory);

			// 最后,发布对应的事件
			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();
		}
	}
}

}

放到set中

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {

private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
}

猜你喜欢

转载自blog.csdn.net/m0_38032682/article/details/88985448