本文要分析的方法:
12.getSingleton(String beanName, ObjectFactory<?> singletonFactory)创建bean实例,bean是单例时,创建单例bean
13.是prototype时,重新创建一个实例
14.其他scope时,使用相应的规则进行创建实例
12.getSingleton(String beanName, ObjectFactory<?> singletonFactory)创建bean实例,bean是单例时,创建单例bean
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
//从singletonObjects缓存容器中取,取到直接返回
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
//判断是否在销毁单例,在则报错
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while the singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
//检查beanName是否正在被创建,在的话不能再创建要报错
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
//从singletonFactory取出实例
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
//检查beanName是否在被创建,不在就报错
afterSingletonCreation(beanName);
}
if (newSingleton) {
把实例加入到缓存
addSingleton(beanName, singletonObject);
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
此方法完成的功能:
1.从singletonObjects缓存容器中取,取到直接返回
2.判断是否在销毁单例,在则报错
3.检查beanName是否正在被创建,在的话不能再创建要报错
4.从singletonFactory取出实例
5.检查beanName是否在被创建,不在就报错
6.把实例加入到缓存
singletonObjects的作用:保存单例实例,在getBean时先从此缓存容器中取。
singletonFactories的作用:保存ObjectFactory对象(是一个代理对象),在getBean时如果在singletonObjects没有取到,则会从singletonFactory中取。
earlySingletonObjects的作用:
registeredSingletons的作用:保存注册了的单例。
12.1createBean方法:
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
// Make sure bean class is actually resolved at this point.
//确保此时已经得到了beanClass
resolveBeanClass(mbd, beanName);
// Prepare method overrides.
try {
//处理重载和重写的方法
mbd.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
//先从bean的后处理器取代理对象,如果有代理对象则直接返回
Object bean = resolveBeforeInstantiation(beanName, mbd);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
//如果没有,则通过beanName,beanDefinition,方法参数来创建bean实例
Object beanInstance = doCreateBean(beanName, mbd, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
此方法完成的功能:
1.确保此时已经得到了beanClass
2.处理重载和重写的方法
3.先从bean的后处理器取代理对象,如果有代理对象则直接返回
4.如果没有,则通过beanName,beanDefinition,方法参数来创建bean实例
12.1.1.resolveBeforeInstantiation(beanName, mbd)方法先从bean的后处理器取代理对象,如果有代理对象则直接返回:
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
//判断是否有beanClass,不是spring系统实例,有InstantiationAwareBeanPostProcessor处理器
if (mbd.hasBeanClass() && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
//调用前处理
bean = applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName);
if (bean != null) {
//调用后处理
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
方法完成的功能:此方法主要检查了需不需要执行InstantiationAwareBeanPostProcessor的处理器,如果需要的话,则执行之后返回代理实例。
12.1.2 doCreateBean(beanName, mbd, args)方法,创建bean实例:
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
//如果是单例从factoryBeanInstanceCache缓存容器中取BeanWrapper 对象
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
//创建BeanWrapper 对象
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
// Allow post-processors to modify the merged bean definition.
//检查是否所有的后处理器已经执行完,没执行完 则执行
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
//为了解决循环依赖,先获取一个bean的代理放入singletonFactories中
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, new ObjectFactory<Object>() {
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//属性注入和校验循环依赖
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
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);
}
}
//提前暴露实例,并校验依赖的实例是否已创建
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
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.");
}
}
}
}
// Register bean as disposable.
try {
//增加bean销毁时的处理器,如在bean中使用了destroy-method方法,或继承了DisposableBean
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
此方法完成的功能:
1.如果是单例从factoryBeanInstanceCache缓存容器中取BeanWrapper 对象
2.通过构造器创建BeanWrapper 对象
3.检查是否所有的后处理器已经执行完,没执行完 则执行
4.为了解决循环依赖,先获取一个bean的代理放入singletonFactories中
5.属性注入和校验循环依赖
6.提前暴露实例,并校验依赖的实例是否已创建
7.增加bean销毁时的处理器,如在bean中使用了destroy-method方法,或继承了DisposableBean
12.1.2 .1createBeanInstance方法通过构造器创建BeanWrapper 对象
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
// Make sure bean class is actually resolved at this point.
//得到bean的class
Class<?> beanClass = resolveBeanClass(mbd, beanName);
//校验beanClass是public修饰,不是要报错
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
//如果有工厂方法,那么使用FactoryMethod进行初始化
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
//如果是无参构造器,已创建则直接调方法创建
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
// Need to determine the constructor...
//没创建则找出构造器进行创建
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
//有参构造器创建
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// No special handling: simply use no-arg constructor.
//无参构造器创建
return instantiateBean(beanName, mbd);
}
此方法完成的功能:
1.得到bean的class
2.校验beanClass是public修饰,不是要报错
3.如果有工厂方法,那么使用FactoryMethod进行初始化
4.如果是无参构造器,已创建则直接调方法创建
5.没创建则找出构造器进行创建
6.autowireConstructor()方法有参构造器创建
7.instantiateBean()方法无参构造器创建
难度在于有参构造器创建实例,因为可能会存在多个构造器的重载,spring使用的方式是先找到所有的beanClass的构造器,然后按构造器参数数量的降序排列,遍历所有的构造器,当参数数量和要求的参数数量相同,再比较参数的类型,都匹配时则找出的要求的构造器,然后通过构造器的反射方法实现实例化过程。
3.applyMergedBeanDefinitionPostProcessors检查是否所有的后处理器已经执行完,没执行完 则执行
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)
throws BeansException {
try {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
catch (Exception ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing failed of bean type [" + beanType + "] failed", ex);
}
}
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
if (beanType != null) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
metadata.checkConfigMembers(beanDefinition);
}
}
此后处理器主要是对@autowired,@value等标签的解析,把相关信息保存在InjectionMetadata对象中,供下面注入时使用。
5.populateBean(beanName, mbd, instanceWrapper)属性注入和校验循环依赖
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues();
if (bw == null) {
if (!pvs.isEmpty()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
boolean continueWithPropertyPopulation = true;
//不知道作用是什么
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
//如果beanDefinition的autowiredMode是AUTOWIRE_BY_NAME 或AUTOWIRE_BY_TYPE,则按照相应的方式进行注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
//用后处理器对使用@autowired,@value, @Qualifier等注解修饰的属性进行注入
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
//把生成的属性对象pvs赋给beanWrapper对象
applyPropertyValues(beanName, mbd, bw, pvs);
}
此方法完成的功能:
1.得到bean的class
2.如果beanDefinition的autowiredMode是AUTOWIRE_BY_NAME 或AUTOWIRE_BY_TYPE,则按照相应的方式进行注入
3.用后处理器对使用@autowired,@value, @Qualifier等注解修饰的属性进行注入
4.把生成的属性对象pvs赋给beanWrapper对象
总结bean实例创建过程:首先通过beanClass的构造器创建beanwrapper对象。然后注入属性生成PropertyValues对象,再把PropertyValues对象放到beanwrapper对象中。最后校验beanwrapper中的bean实例是beanFactory还是普通bean,是beanFactory那么返回代理实例。是普通bean直接返回。此时就创建了完了bean。