protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 初始化名字为conversionService的bean
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);
}
// 停止使用临时类加载器进行类型匹配,置null
beanFactory.setTempClassLoader(null);
// 冻结(this.configurationFrozen = true;)所有beanDefinition,不让bean继续注册
beanFactory.freezeConfiguration();
// 实例化所有剩余的(非延迟-init)单例
beanFactory.preInstantiateSingletons();
}
//---------------------------------
// 实例化所有剩余的(非延迟-init)单例
public void preInstantiateSingletons() throws BeansException {
// 拿到所有beanName 去遍历
//获取所有bean
List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
// 触发所有非懒加载的singleton bean的初始化
for (String beanName : beanNames) {
//将非RootBeanDefinition转换为RootBeanDefinition以方便后续操作,
//因为Spring上下文包括实例化所有Bean用的AbstractBeanDefinition是RootBeanDefinition
//合并bean定义
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//如果当前“不是抽象类 && 是单例 && 不是延迟加载” 则执行
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) { //判断是否factoryBean
//返回一个共享或独立的实例
final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
boolean isEagerInit;
// ......
if (isEagerInit) {
//返回一个实例
getBean(beanName);
}
} else {
getBean(beanName);
}
}
}
//...
}
//进行实例bean的方法,调用getBean方法最后调到doGetBean
//-返回一个指定bean的实例,无论是共享或独立
protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
//去掉beanName前的'&',然后再拿当前beanName去别名aliasMap.get(canonicalName)取
final String beanName = transformedBeanName(name);
Object bean;
// 检查是否已创建过 ,并根据注册给定的名字返回singleton
Object sharedInstance = getSingleton(beanName);
//args为空时是获取bean,不为空是创建bean
if (sharedInstance != null && args == null) {
.........................
//返回对象bean实例,如果是(beanInstance instanceof FactoryBean),则直接返回
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
//检查当前bean是否已被创建,是则抛异常
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 检查bean definition是否在该工厂已创建
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 没找到就去找parent容器
String nameToLookup = originalBeanName(name);
if (args != null) {
// 返回父容器(带参数)
return (T) parentBeanFactory.getBean(nameToLookup, args);
} else {
// 不带参数
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
//typeCheckOnly为true时,将指定的bean标记为已创建,添加进Set<String> alreadyCreated中
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
//合并bean定义
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//检查是否Abstract,是则抛异常
checkMergedBeanDefinition(mbd, beanName, args);
// 获取依赖的bean名称
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
//然后遍历传入进行初始化
for (String dependsOnBean : dependsOn) {
//判断循环依赖
if (isDependent(beanName, dependsOnBean)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
}
registerDependentBean(dependsOnBean, beanName);
//递归获取依赖的bean
getBean(dependsOnBean);
}
}
// 接下来就到了创建一个bean实例的过程,创建单例/多例
//单例模式bean创建
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
} catch (BeansException ex) {
//。。。。。。。。。。。。。。。。
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) { //多例
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
} finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} else { //非单例/多例处理
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
} finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
} catch (IllegalStateException ex) {
//...........
}
}
} catch (BeansException ex) {
// ...........
}
}
// 检查所需的类型是否与实际bean实例的类型匹配。不是则抛出异常
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
} catch (TypeMismatchException ex) {
.............
}
return (T) bean;
}
}
//AbstractAutowireCapableBeanFactory.createBean利会调用该方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
//......
if (instanceWrapper == null) {//实例化bean,调用构造函数
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//......
// 保存单例的实例,解决循环依赖,此时bean还未注入属性
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}//......
try {
//填充bean ,如:bean属性,autowired
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
//初始化bean,调用初始化方法
exposedObject = initializeBean(beanName, exposedObject, mbd);
}//......
}
}
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
//AbstractAutowireCapableBeanFactory.initializeBean
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
//...
} else {
//调用一系列xxxAware接口,如:BeanNameAware
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {//调用BeanPostProcessor的before接口
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//调用bean的初始化方法,InitializingBean.afterPropertiesSet
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {}
if (mbd == null || !mbd.isSynthetic()) {//调用BeanPostProcessor的after接口,后面讲到的AOP的实现的关键,就是在这里对bean进行包装的
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}