接着refresh()
方法的第六步开始写下去:
@Override
public void refresh() throws BeansException, IllegalStateException {
//上锁,保证只有一个线程进入
synchronized (this.startupShutdownMonitor) {
// 1. 准备要刷新的上下文
prepareRefresh();
// 2. 告诉子类去刷新内部的BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 3. 准备当前上下文要用的BeanFactory
prepareBeanFactory(beanFactory);
try {
// 4. 在子类中允许BeanFactory的Post-processing处理
postProcessBeanFactory(beanFactory);
// 5. 调用所有以Bean身份注册的BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);
// 6. 注册拦截Bean创建的processors
registerBeanPostProcessors(beanFactory);
// 7. 初始化上下文的消息来源
initMessageSource();
// 8. 初始化上下文的事件多播器
initApplicationEventMulticaster();
// 9. 在特定的容器子类中初始化特殊的Bean
onRefresh();
// 10. 检查并注册监听器Bean对象
registerListeners();
// 11. 实例化所有的(非懒加载)单例对象
finishBeanFactoryInitialization(beanFactory);
// 12. 最后一步:发布对应的事件
finishRefresh();
}
//捕获 BeansException 异常
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// 销毁已创建的单例对象
destroyBeans();
// 重置“active”标识
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// 重置内省缓存.
resetCommonCaches();
}
}
}
registerBeanPostProcessors
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 通过BeanPostProcessor类型查找bean名称
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// 注册BeanPostProcessor之前的准备
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 优先的PostProcessors
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 内部的PostProcessors
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
// 排序的PostProcessor的名称
List<String> orderedPostProcessorNames = new ArrayList<>();
// 未排序的PostProcessor的名称
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
// 如果实现了PriorityOrdered接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 获取BeanPostProcessor
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
// 放入priorityOrderedPostProcessors集合
priorityOrderedPostProcessors.add(pp);
// 如果是MergedBeanDefinitionPostProcessor,放入internalPostProcessors集合
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
// 如果实现了Ordered接口,将BeanName放入orderedPostProcessorNames集合
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
// 否则只将BeanName放入nonOrderedPostProcessorNames集合
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// 按依赖顺序排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 首先注册实现了PriorityOrdered接口的PostProcessor
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 然后注册实现了Ordered接口的PostProcessor
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 注册其他PostProcessor
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 注册所有MergedBeanDefinitionPostProcessor
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
可见先注册实现了PriorityOrdered接口的PostProcessor,然后是实现了Ordered接口的PostProcessor,然后是普通的PostProcessor,最后是MergedBeanDefinitionPostProcessor。
如何注册:
private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
// 如果原来存在,则移除
this.beanPostProcessors.remove(beanPostProcessor);
// 如果是InstantiationAwareBeanPostProcessor,把hasInstantiationAwareBeanPostProcessors标记为true
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
// 如果是DestructionAwareBeanPostProcessor,把hasDestructionAwareBeanPostProcessors标记为true
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
//添加到beanPostProcessors集合中
this.beanPostProcessors.add(beanPostProcessor);
}
可以看出就是添加到beanFactory的beanPostProcessors集合中,并且可以重复注册,重复注册会将其在集合中的位置移到集合末尾。
initMessageSource
MessageSource用于国际化,过完这个步骤之后IoC容器中可能会存在一个BeanName为"messageSource",类型为MessageSource
的消息源单例对象。
这里不看。
initApplicationEventMulticaster
过完这个步骤之后IoC容器中可能会存在一个BeanName为"applicationEventMulticaster",类型为ApplicationEventMulticaster
的事件广播器单例对象。
这里不看。
onRefresh
通常是Web环境
registerListeners
protected void registerListeners() {
// 注册一些静态特定的listener
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 注册所有以Bean身份注册的ApplicationListener
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 发布早期事件:事件广播器已建立
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
finishBeanFactoryInitialization
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 初始化一个BeanName为"conversionService"的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));
}
// 添加一个嵌入的ValueResolver
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// 先初始化所有实现了LoadTimeWeaverAware接口的Bean
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// 停止使用暂时的类加载器
beanFactory.setTempClassLoader(null);
// 冻结配置更改,允许缓存BeanDefinition元信息
beanFactory.freezeConfiguration();
// 初始化所有的单例对象
beanFactory.preInstantiateSingletons();
}
冻结配置并缓存beanDefinitionNames:
@Override
public void freezeConfiguration() {
this.configurationFrozen = true;
this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
}
注意这里初始化所有的单例对象,此时就是按照单例Bean的名单一个个触发了一下getBean方法,而单独创建一个DefaultListableBeanFactory
是不会启动的时候就实例化这些单例Bean的,这也是ApplicationContext
和BeanFactory
的区别之一:
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// 复制一个beanDefinitionNames的list出来
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 触发所有非懒加载的单例对象的初始化
for (String beanName : beanNames) {
// 获取BeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 不是抽象、是单例、不是懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 如果是一个FactoryBean对象
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
// 如果是普通的bean对象,调用getBean获取
else {
getBean(beanName);
}
}
}
// 触发所有的初始化后的回调(实现了SmartInitializingSingleton接口)
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
可以看出,就是调用getBean
方法触发单例对象的初始化,而getBean
方法我们已经在IOC容器启动源码第3、4、5步分析-容器加载了哪些非Bean对象?中看过了,其触发的创建Bean对象的方法createBean
也在IOC容器启动源码第5步分析续-createBean到底是怎么实现的?中看过了,这里就不重复了。最终创建的单例Bean对象会放入disposableBeans
集合中。
finishRefresh
初始化完所有的单例对象后,就是最后一步finishRefresh
了:
protected void finishRefresh() {
// 清除上下文级别的资源缓存
clearResourceCaches();
// 初始化声明周期处理器
initLifecycleProcessor();
// 生命周期处理器触发refresh
getLifecycleProcessor().onRefresh();
// 发布 ContextRefreshedEvent 事件
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
第二步initLifecycleProcessor
:
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//如果存在名为"lifecycleProcessor"的bean对象,获取并赋值给类中的字段
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
if (logger.isTraceEnabled()) {
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
// 否则进行创建
else {
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
LifecycleProcessor主要是负责实现了SmartLifecycle
的bean的管理。其他的步骤就不看了。
原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/ioc%e5%ae%b9%e5%99%a8%e5%90%af%e5%8a%a8%e6%ba%90%e7%a0%816-12%e6%ad%a5%e5%88%86%e6%9e%90-%e8%a7%a6%e5%8f%91%e5%8d%95%e4%be%8bbean%e7%9a%84%e5%88%9d%e5%a7%8b%e5%8c%96/