本章目标
1.doCreateBean
AbstractAutowireCapableBeanFactory的doCreateBean方法就是核心的生成bean实例的地方
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
是单例的情况下看看该beanName有没有对应的factoryBean,并通过factoryBean得到bean
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
工厂方法,构造函数自动装配或简单实例化来创建实例
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
应用MergedBeanDefinitionPostProcessors的postProcessMergedBeanDefinition
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
是否需要提前曝光的条件=单例&允许循环依赖&当前bean正在创建
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
如果singletonObjects没有当前的BeanName,singletonFactories添加当前的beanName和,singletonFactory,删除earlySingletonObjects中的beanName和Bean
registeredSingletons注册该Bean
addSingletonFactory(beanName, () ->
getEarlyBeanReference是调用SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference,这里会把advice织入bean
getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
填充bean的属性
populateBean(beanName, mbd, instanceWrapper);
调用初始化方法,有可能把bean包装成proxy
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
如果刚刚bean提前曝光了,则在这边
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
代表bean没有被增强
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
当bean创建完成后其所依赖的应该都完成了,如果没完成就存在循环依赖
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
注册bean disposable
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
一. 如果在resolveBeforeInstantiation中创建了代理(需要我们如有自定义TargetSource才可以创建代理)或者修改了InstantiationAwareBeanPostProcessor类的postProcessBeforeInstantiation ,并通过他生成bean,则不会调用doGetBean,否则就会调用普通的bean生成逻辑
二. populateBean(beanName, mbd, instanceWrapper);
1.首先如果instanceWrapper为null 且有propertyValue则抛出异常
2.其次如果没有propertyValue则说明没有属性需要填充直接返回。
3.如果mbd不是合成的(即是由application本身生成的)且包含InstantiationAwareBeanPostProcessors,则调用postProcessAfterInstantiation,该方法主要返回true或者false,true时候我们会给该bean注入属性,否则不注入属性,只要有一个返回false 我们都不注入属性
4.然后判断是根据名称或者类型进行属性注入
5.如果存在InstantiationAwareBeanPostProcessors 或者需要检测依赖,如果存在后置处理器 调用其InstantiationAwareBeanPostProcessor,如果返回的PropertyValues伪null 直接终止后续操作,若需要检测依赖,执行依赖性检查,检查bean所有已公开的属性是否已设置,最终PropertyValues还不为空就开始赋值
三.initializeBean(beanName, exposedObject, mbd)
1.调用invokeAwareMethods
2.应用BeanPostProcessorsBeforeInitialization 即在bean初始化之前调用
3.调用初始化方法invokeInitMethods,除了先调用使用自定义实现InitializingBean接口,调用afterPropertiesSet,然后调用bean的init的方法
4.应用BeanPostProcessorsAfterInitialization 即在初始化之后调用
四. 检测循环依赖情况下 bean的依赖是否都成功加载了
五. 注册实现了disposableBean的bean的,使用DestructionAwareBeanPostProcessor来处理,并且注册DestructioDestructionCallback的回调
总结:spring 系列到此暂告一段落,后面开始研读netty源码,在研究netty的同时,还会每天回顾spring中至今不太熟悉的内容。大致如下:
1.springboot启动的流程图
2.spring启动的流程图
3.spring aop 总结
4.spring ioc的总结
5.内嵌式tomcat