AbstractApplicationContext#finishBeanFactoryInitialization
- 基本这里就到了bean生成的最重要的方法了.
先说说前面几个方法, 很简单就不做细致的源码debug分析了
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
// 初始化事件广播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// springboot启动的AnnotationConfigServletWebServerApplication本身没有做任何实现.
// 不过他们的父类做了些实现比如ServletWebServerApplicationContext
// 会创建webserver
// springboot的Tomcat initialized with port(s): 8089 (http)这句日志就是这个阶段输出的
onRefresh();
// Check for listener beans and register them.
// 添加所有监听器,
registerListeners();
- 现在就开始介绍今天的重点方法finishBeanFactoryInitialization
这方法会创建剩余的所有还未创建的bean的实例.
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
// 初始化转换服务
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));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
// 配置默认的嵌入式值解析器, 如果没有配置就配置一个默认的
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
// 初始化LoadTimeWeaverAware, 这个和aop有关, 要使用这个需要配置@EnableLoadTimeWeaving .
// 我也暂时不是很懂, jpa用到这个
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
// 前面某章启用了临时类加载器, 这里停止使用
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// 冻结所有的beandefinition, 注册的bean的元数据在这个阶段就不能修改了
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 这里是最重点 实例化所有剩余的非懒加载的单例
beanFactory.preInstantiateSingletons();
}
- 接下来主要分析
beanFactory.preInstantiateSingletons()
, DefaultListableBeanFactory实现的ConfigurableListableBeanFactory的接口方法.
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
// 首先获取到所有说有的bean名称, 以允许以init方法住的beandefinition
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
// 遍历创建所有的bean
for (String beanName : beanNames) {
// getMergedLocalBeanDefinition这个方法是返回一个合并的RootBeanDefinition
//
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
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);
}
}
}
else {
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
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();
}
}
}
}