之前的博客专门分析了一个类到BeanDefinition的创建过程,现在分析BeanDefinition 到一个bean的创建过程:从refresh() 方法的---->finishBeanFactoryInitialization(beanFactory) 开始:
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 像容器中设置一个类型转换器
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));
} //设置一个占位符解析器
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
} // loadTimeWeaver是用于类加载阶段做切入使用的
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); // 冻结beanDefinition信息,也就是下面要开始创建对象了,所以不允许再改变了
beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons. //开始实例化所有的单例bean
beanFactory.preInstantiateSingletons();
}
小结:该方法主要是在单例bean开始初始化前,对beanFactory设置一些初始化信息,最重要的还是: beanFactory.preInstantiateSingletons();
public void preInstantiateSingletons() throws BeansException {
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); //获取所有的beanNams 然后遍历每个beanName,获取其BeanDefintion,然后一个个的创建实例 // Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //这里为何是获取MergeBeanDefinition呢,原因是在xml时代,一个bean 可以通过继承一个抽象的bean,来获得初始化的属性
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //在这里的beanDefinition必须不是抽象的,并且是单例,非懒加载的
if (isFactoryBean(beanName)) { //如果是FactoryBean,通过get(BeanName)方式获取的是里面的getObject()返回的对象,如果是get("&beanName")的方式,就是获取到FactoryBean本身
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);//get("&beanName")方式,获取到FactoryBean本身
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) { //这里的意思是,是否要那么早初始化FactoryBean里面的getObject()对象,默认是用到时才会初始化
getBean(beanName);//这里调用的是FactoryBean里面的getObject()
}
}
}
else {
getBean(beanName);//非factoryBean就开始创建对象,factoryBean 也是调用该方法创建对象,只是beanName不一样getBean(FACTORY_BEAN_PREFIX + beanName)
}
}
} // Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) { //至此,所有的实例对象都创建完毕,对于实现SmartInitializingSingleton的bean,在这里会统一调用afterSingletonsInstantiated()
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();
}
}
}
}
小结:上面方法主要逻辑是:遍历所有的bean的定义信息,然后分别创建实例,这里区分了FactoryBean和普通Bean的创建过程,所有Bean都创建完毕后,会对实现SmartInitializingSingleton接口的bean,调用afterSingletonsInstantiated()
//接下来我们分析下单个bean的创建过程:getBean(beanName)
//下面参数的意思: name或者requiredType的意思是通过名称还是通过类型获取对象,args的意思是,如果是通过有参构造器去创建的bean,需要该实参,typeCheckOnly的意思是,我只是想获取返回的类型而不是对象,例如我想知道某个beanName的类型
//一般typeCheck是用于FactoryBean校验里面的getObject()返回的类型
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name);//这里的意思的,在xml时代,一个bean可以拥有多个别名,如果你是通过别名来创建对象的话,这里就会转成对应的BeanName,因为BeanName才是唯一的
Object bean; // Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);//校验实例对象是否已经存在了
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {//判断singletonsCurrentlyInCreation集合有没有该bean,有就代表正在创建中
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);//这里的意思是:既然bean已经创建了,如果是FactoryBean,那么这里就要返回FactoryBean里面的Object对象,其他的Bean直接返回
} else {
//该方法只有非单例才会出现,这里是判断prototypesCurrentlyInCreation有没包含该BeanName,prototypesCurrentlyInCreation是一个ThreadLocal,所以存在代表创建了2次
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
} // Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //这里面的逻辑是,如果BeanFactory并没有包含该Bean的定义信息,那么久去找其父类,看看父类有没该bean
// Not found -> check parent. //查找父类看看有没该Bean
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args. //使用有参构造器去创建实例
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);//通过类型去创建实例
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);//通过名称去创建实例
}
} if (!typeCheckOnly) {
markBeanAsCreated(beanName); //这里的意思是,本次调用方法,并非是要获取bean的类型,而是为了创建实例,将beanName存到alreadyCreated集合,代表该bean已经创建了,后面try。。catch有异常会清空该beanName
} try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);//mergeBeanDefinition的作用是解决xml时代,bean继承一个抽象bean,获取其对应属性,类之间并非真的是继承关系
checkMergedBeanDefinition(mbd, beanName, args);//这里检查mbd是否是抽象的,抽象的话就不能创建 // Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn(); //这里是解决@DependsOn("xx")注解的作用,该注解的作用是,创建某个Bean前,必须先创建xx,xx可以是个数组
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) { //判断是否相互之间有依赖关系,这个要结合下面代码registerDependentBean(dep, beanName);才好理解
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep); //先创建依赖的Bean
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
} // Create bean instance.
if (mbd.isSingleton()) { //如果是单例,就通过调用该方法创建
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);//这里的意思前面也分析过了,意思是,如果是FactroyBean,就调用其getObject()方法,返回对应的对象
} else if (mbd.isPrototype()) { //如果是非单例
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);//存到prototypesCurrentlyInCreation这个ThreadLocal中,代表正在创建
prototypeInstance = createBean(beanName, mbd, args);//该方法跟单例创建实例调用的逻辑是一样的,后续会分析
}
finally {
afterPrototypeCreation(beanName);//既然创建完毕,那么久可以从ThreadLocal中移除该bean了
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);//这里逻辑前面分析过了
} else {
String scopeName = mbd.getScope(); //@Scope标注的bean 下面的逻辑跟创建非单例(原型protoType)bean一样
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);//前面做了markBeanAsCreated(beanName)代表该bean已经创建,失败后,这里就要删除
throw ex;
}
} // Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) { //如果我们需要的类型跟获取的不一致,那么就要转换
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
//小结:上面主要对不同的bean类型做了不同的操作,同时对依赖关系的bean也做了处理,主要方法:createBean(beanName, mbd, args)
后续有一个方法会经常用到,在这里提前分析:Object sharedInstance = getSingleton(beanName,true);
//该方法可以解决循环依赖,也就是A和B相互依赖,例如使用@autowried注解
protected Object getSingleton(String beanName, boolean allowEarlyReference) {//allowEarlyReference代表是否允许循环依赖
Object singletonObject = this.singletonObjects.get(beanName);//我们创建的单例bean都会存在该Map中,如果已经创建,那么久可以获取到,我们可以把它看作一级缓存
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//当一个Bean正在创建中此时已经new出来目标对象了,只是还没有经过后置处理器处理,所以此时它是正在创建中,A依赖B,然后创建B,发现B依赖A,那么久会创建A,创建A时,发现A已经正在创建了
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName); //先从二级缓存获取
if (singletonObject == null && allowEarlyReference) {//获取不到
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); //再从三级缓存获取,该缓存是一个单例工厂
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();//工厂中获取对象
this.earlySingletonObjects.put(beanName, singletonObject);//存入二级缓存
this.singletonFactories.remove(beanName);//移除工厂 那么问题:为何要有二三级缓存?原因是工厂里面的方法可能会很复杂,所以工厂获取对象后,存到二级缓存中,下次再次获取就更高效率了
}
}
}
}
return singletonObject;
}
//接下来,我们来分析bean的创建过程createBean(beanName, mbd, args),由于单例创建过程内容多点,我们从单例的代码入手:
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName); //先从单例缓存中获取
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) { //判断beanFactroy是否正在执行销毁操作
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
}
beforeSingletonCreation(beanName);//存beanName到singletonsCurrentlyInCreation集合,代表单例bean正在创建
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);//用于记录异常用,不是我们关心的点
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
singletonObject = singletonFactory.getObject();//调用工厂方法,也就是我们说的createBean(beanName, mbd, args)
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;
}
afterSingletonCreation(beanName); //从singletonsCurrentlyInCreation集合中移除该beanName,因为已经创建完毕了
}
if (newSingleton) {
addSingleton(beanName, singletonObject);//这里逻辑是将该单例bean添加到this.singletonObjects.put(beanName, singletonObject);和 this.registeredSingletons.add(beanName);
}
}
return singletonObject;
}
}
//小结:上面方法的核心逻辑是:设置单例bean正在创建中,创建完毕后,存到缓存;接下来我们要分析的是:createBean(beanName, mbd, args)
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException { RootBeanDefinition mbdToUse = mbd; // Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);//获取真实的类型
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd); //这里新创建一个mbd 防止被其他线程更改
mbdToUse.setBeanClass(resolvedClass);
} // Prepare method overrides.
try {
mbdToUse.prepareMethodOverrides(); //用于校验@lookup注解相关的处理校验
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
} try {
// InstantiationAwareBeanPostProcessor 后置处理器执行postProcessBeforeInstantiation() 方法
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) { //如果后置处理器获得了代理对象就返回去
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
} try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args); //这里是核心
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
小结:该方法主要是在bean实例化前对bean执行后置处理器InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation(beanClass, beanName);
下面跟进: Object beanInstance = doCreateBean(beanName, mbdToUse, args);
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException { // Instantiate the bean.
BeanWrapper instanceWrapper = null; //对实例对象进行包装
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); //缓存中获取
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args); //创建bean实例,后续会重点关注
}
final Object bean = instanceWrapper.getWrappedInstance(); //获取目标bean
Class<?> beanType = instanceWrapper.getWrappedClass(); //获取类型
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;//修改beanDefinition的目标对象类型
} // Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {//调用MergedBeanDefinitionPostProcessor 后置处理器的postProcessMergedBeanDefinition(mbd, beanType, beanName); 允许修改mbd
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
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是正在创建的,很明显,符合要求
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//工厂方法会调用SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference(Object bean, String beanName)
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); //设置单例的二级缓存this.singletonFactories.put(beanName, singletonFactory);
} // Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper); //给属性赋值(后续会分析)
exposedObject = initializeBean(beanName, exposedObject, mbd);//执行init 方法(后续会分析)
}
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);//当有循环依赖时,这里就会从二级缓存中获取到早期的bean,如果没有循环依赖,这里获取到的是null
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
//如果不相等,例如使用@Async注解标注的bean,调用initializeBean(beanName, exposedObject, mbd);获得的是一个代理对象,因此exposedObject是代理对象,而bean还是原生对象,通过二级缓存得到的是原生对象
//如果循环依赖的bean已经创建完了,说明他们依赖的是原生的Bean而不是代理的bean,这样就会报错
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(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 {
registerDisposableBeanIfNecessary(beanName, bean, mbd); //有detroy方法的bean就会收集起来,当容器销毁时,就可以调用这些bean的destroy方法
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
} return exposedObject;
}
小结:该方法的核心是:创建bean的实例(createBeanInstance(beanName, mbd, args); ),进行属性赋值( populateBean(beanName, mbd, instanceWrapper);),执行init方法(initializeBean(beanName, exposedObject, mbd);),注册有detroy方法的bean,下面分别分析这三个方法:
1.createBeanInstance(beanName, mbd, args);
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName); //获取实际的类型 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { //如果不是public修饰的,代表不能访问
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
} Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);//如果有实例工厂,直接调用工厂方法
} if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);//如果是@bean修饰的方法,那么调用该方法即可(反射调用)
} // Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) { //如果是第二次创建相同bean,如原型对象,他们的beanDefinition对象已经知道用哪个构造器或者工厂方法了,此时就直接调用对应方法即可
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {//之前已经调用过了,这里直接调用对应方法,根据构造器参数是否已经解析了来处理
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
} // Candidate constructors for autowiring?
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); //第一次解析,就要获取合适的构造器
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
} // Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();//如果有默认的合适构造器
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
} // No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);//上面都不满足,那么只能调用无参构造器了
}
小结: 该方法的作用是通过工厂方法或者@bean注解标注的方法或者构造器来进行对象的实例化
2. populateBean(beanName, mbd, instanceWrapper); bean的属性赋值
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {//如果bean实例为空,但mbd有属性
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, //实例化之后,属性赋值之前执行InstantiationAwareBeanPostProcessor
// 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) { //如果后置处理器返回为false后就不能走下去了
return;
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) { //这里不看,这里是旧逻辑了,xml时代的
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
} boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
//这里才是核心,我们的@Autowired 和 @Value注解注入的属性就是在这里实现的,后置处理器是:AutowiredAnnotationBeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
} if (pvs != null) { //这里不看,这里是旧逻辑了,xml时代的 复杂
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
小结:上面方法主要的核心是:1.在bean的实例化之后,属性赋值之前执行了InstantiationAwareBeanPostProcessor后置处理器的postProcessAfterInstantiation(bw.getWrappedInstance(), beanName) 2.@autowried和@value的属性赋值实现逻辑是通过InstantiationAwareBeanPostProcessor的.postProcessProperties(pvs, bw.getWrappedInstance(), beanName)方法实现
3.exposedObject = initializeBean(beanName, exposedObject, mbd);
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean); //调用aware接口的实现方法,例如ApplicationContextAware的setApplicationContext()方法
} Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {//Synthetic 这个的意思是,类或者方法不是由开发人员自己定义的,而是jvm帮忙创建的
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); //执行BeanPostProcessor的applyBeanPostProcessorsBeforeInitialization方法
} try {
invokeInitMethods(beanName, wrappedBean, mbd);//执行init方法
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);//执行BeanPostProcessor的
} return wrappedBean;
} private void invokeAwareMethods(final String beanName, final Object bean) { //aware方法的逻辑
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
init方法的执行:
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable { boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet(); //如果实现了InitializingBean 就调用该方法
}
} if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);//如果有自定义的init方法,例如@Bean(initMethod ="hello" )
}
}
}
至此,一个bean的创建过程分析完毕
最后一张图总结bean创建的过程: