利用BeanDefinition创建对象,注册到容器中
先上流程图,自己画的,勿喷!!!
直接上代码:
/**
* 实例化容器中所有的bean定义
* @throws BeansException
*/
@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定义的名称
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
//循环bean定义名称,实例化所有不是懒加载的bean定义
for (String beanName : beanNames) {
//合并bean定义,转换成统一的RootBeanDefinition,方便后面处理,所谓的合并bean定义,就是对Bean定义进行在封装,
//新增bean的信息属性
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//bean定义不是抽象的 是单列的 不是懒加载的
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//对实现FactoryBean接口对象进行处理
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
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 {
//这一步是对常规的bean进行实例化
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
//利用别名获取bean的name 去除 &
String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//在一、二、三级缓存中利用beanName进行查找,但是可能是一个没有属性赋值的对象
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
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 + "'");
}
}
//这一步是针对FactoryBean做处理的,如果是常规的bean,就会原样返回;如果name中有&开头
//则把bean定义标记为factoryBean并且原样返回,如果是FactoryBean并且name中没有&开头,则返回getObject里的对象
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
//如果二三级缓存中都没有,并且正在创建的集合中有,则报异常
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
//检查bean定义是否在父容器中
BeanFactory parentBeanFactory = getParentBeanFactory();
//如果父容器不为null,并且当前容器没有此bean定义
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
//返回原来的名称:如果是别名则返回真正的名称,如果是有&开通的,则返回&开头的真正名称
String nameToLookup = originalBeanName(name);
//以下创建bean先不看,因为是和常规实例化bean的流程是一样的,后面再看
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);
}
}
//常规typeCheckOnly=fales,所以会进入;标记特殊的类以及创建了,把它放在缓存alreadyCreated中,以便重复利用
//标记bean定义重新需要合并(重新创建rootBeanDefinition),以防万一它的某些元素据发生了变化
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
//重新合并bean定义
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//检查Bean定义是否是抽象的
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//处理@DependsOn("person")注解的;如果有这个注解,那先创建该注解的bean对象
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
//是个数组
for (String dep : dependsOn) {
//如果当前bean定义依赖的bean也依赖了当前的bean定义,则会报错;
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
//加入到缓存中dependentBeanMap /把依赖的beanName作为key加入dependentBeanMap
// value为LinkedHashSet,存的是当前的beanName;;是给上一步@DependsOn注解相互依赖判断的
registerDependentBean(dep, beanName);
try {
//递归调用 getBean方法进行对象的实例化
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
//但其Bean定义是单例的
if (mbd.isSingleton()) {
//这一步是创建对象的核心步骤,传入的参数为: 当前beanName 一个创建对象的核心执行函数
sharedInstance = getSingleton(beanName, () -> {
try {
//创建对象的核心方法:
//beanName当前beanName mbd: 当前RootBeanDefinition args:常规创建默认为null使用无参构造方法创建对象
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);
}
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();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
}
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);
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;
}
/**
* 通过名称获取对象
* @param beanName
* @param allowEarlyReference
* @return
*/
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock
//先从一级缓存中获取
Object singletonObject = this.singletonObjects.get(beanName);
//如果已经缓存没有获取到,并且singletonsCurrentlyInCreation正在创建的集合中也没有;
//当前猜测是因为在二、三级缓存的都应该是正在创建中
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//二级缓存中获取,二级缓存是装载那些实例化但是没有属性赋值的对象
singletonObject = this.earlySingletonObjects.get(beanName);
//二级缓存中也没有获取到
if (singletonObject == null && allowEarlyReference) {
//加锁
synchronized (this.singletonObjects) {
// Consistent creation of early reference within full singleton lock
//再检查一下一级缓存
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
//再检查二级缓存
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
//再从三级缓存中获取,所谓的三级缓存是装载对象创建的函数对象,调用这个函数就能返回对应的对象
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
//如果三级缓存中获取到
if (singletonFactory != null) {
//创建对象,这个时候可能有循环依赖,所以可能是那些没有属性赋值的对象;
singletonObject = singletonFactory.getObject();
//加入到二级缓存中
this.earlySingletonObjects.put(beanName, singletonObject);
//移除三级缓存中的对象
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
//name是否以&开通
if (BeanFactoryUtils.isFactoryDereference(name)) {
//是否是NullBean
if (beanInstance instanceof NullBean) {
return beanInstance;
}
//如果不是FactoryBean就抛异常
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
if (mbd != null) {
mbd.isFactoryBean = true;
}
//直接返回对象
return beanInstance;
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
//如果不是FactoryBean 则直接返回
if (!(beanInstance instanceof FactoryBean)) {
return beanInstance;
}
//如果是FactoryBean但是名称中没有&符号,则执行以下逻辑 返回getObject方法中返回的bean
Object object = null;
if (mbd != null) {
mbd.isFactoryBean = true;
}
else {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
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) {
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!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
//判断当前创建对象排除的集合中有没有此beanName,如果包含,则抛异常
//查询当前正在创建对象的beanName集合singletonsCurrentlyInCreation中是否包含此对象,如果包含则抛异常
//若第二次循环依赖进入到这个步骤是就会抛异常;
//因为如果是通过getBean获取相同的对象时,比如循环依赖:自己先主动通过getBean方法创建对象,然后触发循环依赖再次getBean
//获取此对象时就不会走到此步骤,因为在这之前会检查一下一二三级缓存,第二次getBean相同的bean时,三级缓存中已经存在了,肯定不会
//走到此处
//走到此处出现异常的情况:构造函数的循环依赖:
/**
* Car.java中
* @Autowired(required = false)
* public Car(Person person) {
* this.person = person;
* System.out.println("Car使用此构造函数实例化+person");
* }
*
* Person.java中
* @Autowired
* private Car car;
*
* 如果先加Car会在此处出现异常,先加载Person则不会出现循环依赖的异常
* 异常分析:实例化Person时触发getBean Person 又反过来出发getBean Car,因为此时Car构造器依赖,所以没有在三级缓存中;就会到
* 此不走出现循环依赖的异常
*
* 相同的情况:如果先创建Person对象则不会出现异常:原因就是Car出发getBean Person是,Person已经在三级缓存中了。
*
*/
beforeSingletonCreation(beanName);
boolean newSingleton = false;
//创建转载异常的集合,如果不为null,则不创建,
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
//这一步是非常重要的:是创建对象的核心:调用回调函数,创建对象
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;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
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.
//获取bean定义的class对象,检查这个点的bean定义是否有Class对象,给复制bean定义的beanClass赋值;完全是为了确认一下
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
//处理XLM方式的lookup-method 和 replace-method,生成代理对象;暂时不看;等整个流程结束后再看
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
//给beanPostProcessors后置处理器一次机会返回代理对象
//有两个逻辑:一个是执行InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation(Class<?> beanClass, String beanName)方法
//如果返回了代理对象,则再实现BeanPostProcessor接口的后置处理器的postProcessAfterInitialization(Object bean, String beanName)方法,
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
//如果InstantiationAwareBeanPostProcessor后置处理器创建了代理对象,则直接进行返回
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
//创建bean,核心逻辑
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);
}
}
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
//BeanWrapper 是对 Bean 的包装,其接口中所定义的功能很简单包括设置获取被包装的对象,获取被包装 bean 的属性描述器
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
//删除缓存中没有完成的factoryBean
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
//如果缓存中没有相对应的factoryBean,则进行封装bean的创建
if (instanceWrapper == null) {
//这一步是实例化bean,并封装成BeanWrapper进行返回;这一步的逻辑还是比较多的;其中比较重要的是选择构造函数进行实例化
//也包括了@Bean注解的工厂方法实例化
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//获取实例化的对象
Object bean = instanceWrapper.getWrappedInstance();
//获取class对象
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
//是否允许 后置处理器去更新和合并bean定义
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//传参为 bean定义 bean类型、beanName
//进行后置处理 @AutoWired @Value @Resource @Persistence的注解的预解析 做一次检查
//利用的是MergedBeanDefinitionPostProcessor后置处理器
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.
//加入正在创建的集合中是在,执行singletonFactory.getObject()方法之前
//是否允许暴露早期对象
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//加入到三级缓存中;value为 ObjectFactory<?> singletonFactory类型的接口函数;目的是获取对象时:
//执行SmartInstantiationAwareBeanPostProcessor后置处理器的getEarlyBeanReference方法后返回的对象加入到一级缓存中
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//进行属性赋值
populateBean(beanName, mbd, instanceWrapper);
//执行一些回调方法和初始化方法,执行实现PostProcess后置处理器的方法;这一步可以返回代理对象
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) {
/**
* 去缓存中获取到我们的对象 由于传递的allowEarlyReference 是false 要求只能在一级二级缓存中去获取
* 正常普通的bean(不存在循环依赖的bean) 创建的过程中,压根不会把三级缓存提升到二级缓存中
* 所以只能存在一个情况:A依赖B B依赖A ,如果A先执行getBean则,会在此处获取到值,进入判断
*
*/
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
//经过后置处理的bean和早期的bean引用还相等的话(表示当前的bean没有被代理过)
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
//如果当前初始化完成的对象和在二级缓存中的对象不一样,说明在初始化的时候创建了代理类
//dependentBeanMap记录相互依赖的缓存,key为被依赖的beanName value为依赖的beanName集合
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
//如果存在依赖当前对象的bean
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
//赖当前对象的bean已经创建
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 " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
//注册销毁的bean的销毁接口 DisposableBean AutoCloseable DestructionAwareBeanPostProcessor
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
//确定和获取class对象
Class<?> beanClass = resolveBeanClass(mbd, beanName);
//判断bean定义是否有class对象、获取clss对象是否是public的、确定bean定义是否有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());
}
//该方法是spring5.0 新增加的 如果存在 Supplier 回调,则使用给定的回调方法初始化策略
//这个常规是没有值的;如果需要用需要手动赋值,创建的对象就是这个函数的返回值
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
//这个通过工厂方法创建对象:也就是@Bean注解
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
/**
*
* 以下判断当前bean定义是否被用来实例化过对象;如果实例化过,则Executable resolvedConstructorOrFactoryMethod属性会
* 缓存使用实例化对象的构造函数,减少了推断使用哪种方式实例化对象以提高效率,比如创建多利Bean对象的时候走此捷径
* 但第一次使用当前Bean定义实例化对象是,它的resolvedConstructorOrFactoryMethod会被设置
*/
//标识bean定义是否被创建过对象
boolean resolved = false;
boolean autowireNecessary = false;
//如果传入的构造函数参数不为null,则就能推断出创建对象使用的构造函数
if (args == null) {
//加上锁,防止并发对此bean定义的对象那创建判断
synchronized (mbd.constructorArgumentLock) {
//Executable resolvedConstructorOrFactoryMethod; 判断当前bean定义是否缓存创建对象的使用的构造函数或者工厂方法,
//以减少推断使用哪一个构造函数来实例化对象
if (mbd.resolvedConstructorOrFactoryMethod != null) {
//标识该Bean定义已经被解析过
resolved = true;
//bean定义的constructorArgumentsResolved这个字段标识的是是否使用有参构造函数进行实例化的
//比如以下这种方式会走有参构造参数实例化
// @Autowired
// public Person(Car car){
// System.out.println("person 有参构造函数实例化");
// }
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
//若已经解析过
if (resolved) {
//使用有参的构造函数利用反射进行实例化;
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
//无参构造函数的实例化
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
//选择候选的构造器注入实例化实例的构造函数,传入的参数为当前bean的class对象、beanName 使用的是AutowiredAnnotationBeanPostProcessor后置处理器
//这里面的逻辑还是比较多的,大致如下:把所有@Autowired注解的构造函数作为候选的对象,如果存在多个@Autowired注解的构造函数,则不能存在requred=true
//构造函数,否则会报错 ;会把所有@Auwired注解的构造函数对象包括无参的构造函数都作为候选的对象;
//如果存在只有多个有参的但是没有@Autowired注解的构造函数,则会报异常,因为默认使用的是无参构造函数;
//如果存在requred=ture的注解,则作为唯一的候选的构造函数对象
//如果只存在一个有参的构造函数,则作为候选对象
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?
//bean定义中设置了优先使用的构造函数,则进行实例化
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
//如果没有有参的构造函数,则默认使用无参构造函数进行实例化
return instantiateBean(beanName, mbd);
}
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
throws BeanCreationException {
/**
* 关于@Lookup注解的使用方法是:
* 如果在一个对象中获取其属性注入的对象,虽然注入的对象是单例存在的,但是我们获取 到的注入对象永远是不变的
* 如果我们想获取其多利对象;则需要在其获取的方法上加上@Lookup注解就可以每次都能获取到多利的属性对象了;
*/
// Let's check for lookup methods here...
//检查一下 方法中是否有@Lookup注解
//检查当前@Lookup注解的缓存中是否有beanName
if (!this.lookupMethodsChecked.contains(beanName)) {
//发现这个判断的逻辑有问题:如果beanClass的全限定名以java.开头或则== Ordered.class 则返回false, 其它的都是返回true
if (AnnotationUtils.isCandidateClass(beanClass, Lookup.class)) {
try {
Class<?> targetClass = beanClass;
do {
//下面的逻辑就是找到beanClass里的所有Method方法对象,然后遍历以每个方法对象为参数执行下面的函数接口逻辑
//这些的逻辑就是:把有@Loockup注解的方法和其注解里的value值封装成LookupOverride对现象,然后添加到bean定义
//的methodOverrides属性对象的集合中
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
//获取当前方对象是否有@Loockup注解
Lookup lookup = method.getAnnotation(Lookup.class);
//如果由此注解则执行判断里的逻辑代码
if (lookup != null) {
Assert.state(this.beanFactory != null, "No BeanFactory available");
//把Method方法对象和@Loockup注解的value值封装成LookupOverride对象
LookupOverride override = new LookupOverride(method, lookup.value());
try {
//根据beanName在容器中获取bean定义
RootBeanDefinition mbd = (RootBeanDefinition)
this.beanFactory.getMergedBeanDefinition(beanName);
//有@Lookup注解的方法封装的LookupOverride对象添加到bean定义的MethodOverride的属性中
mbd.getMethodOverrides().addOverride(override);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(beanName,
"Cannot apply @Lookup to beans without corresponding bean definition");
}
}
});
//这一步是需要便利当前bean的所有父类对象检查@Loockup注解
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
}
}
//把已经检查了@Loockup注解的beanName加入到指定的集合中
this.lookupMethodsChecked.add(beanName);
}
// Quick check on the concurrent map first, with minimal locking.
//首先class对象检查当前缓存中是否有对应的候选构造函数对象
Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
//如果缓存中没有,则需要自己进行获取
if (candidateConstructors == null) {
// Fully synchronized resolution now...
//先加锁,这样一次只能有一个bean进行和候选构造函数的获取
synchronized (this.candidateConstructorsCache) {
//在一次检查一下缓存
candidateConstructors = this.candidateConstructorsCache.get(beanClass);
if (candidateConstructors == null) {
//定义一个原始的候选构造函数对象数组对象
Constructor<?>[] rawCandidates;
try {
//根据class对象获取所有的构造函数对象
rawCandidates = beanClass.getDeclaredConstructors();
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Resolution of declared constructors on bean Class [" + beanClass.getName() +
"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
}
//定义一个候选的构造函数集合
List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
Constructor<?> requiredConstructor = null;
Constructor<?> defaultConstructor = null;
//找到首选的构造函数对象,不知道原理;但是通过debug发现,这个一般为null
Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
//这个是统计当前bean有多是个非合成的构造函数
int nonSyntheticConstructors = 0;
for (Constructor<?> candidate : rawCandidates) {
//是不是合成方法:如果不是则会进入判断 合成方法是那些 通过.java文件编译后由jvm生产的方法;
if (!candidate.isSynthetic()) {
//如果不是合成的构造方法,则变量加一
nonSyntheticConstructors++;
}
else if (primaryConstructor != null) {
//如果当前构造函数对象是jvm合成的,并且首选的构造器对象不为null,则循环continue
continue;
}
//获取当前构造函数对象上的@Autowired注解对象
MergedAnnotation<?> ann = findAutowiredAnnotation(candidate);
//这个逻辑:但当前候选构造器对象上没有@Autowired注解,则再检查一次:如果beanClass是cglib增强后的,并且
//父类中存在与当前候选构造函数对象的参数类型匹配的构造函数对象,则再获取父类匹配构造函数的@Autowired注解
if (ann == null) {
//获取逻辑:如果beanClass是cglib增强的并且父类不是object类型的,则返回父类的class对象,否则还是返回原BeanClass对象
Class<?> userClass = ClassUtils.getUserClass(beanClass);
//如果获取到的class对象和当前beanClass对象不一样,则是获取了cglib增强的不是Object类型的父类对象
//说明当前的beanClass是被cglib真强后的class
if (userClass != beanClass) {
try {
//根据当前候选的构造函数类型列表数组匹配获取父类的所有构造器对象
Constructor<?> superCtor =
userClass.getDeclaredConstructor(candidate.getParameterTypes());
//找到@Autowired注解的构造器
ann = findAutowiredAnnotation(superCtor);
}
catch (NoSuchMethodException ex) {
// Simply proceed, no equivalent superclass constructor found...
}
}
}
//如果存在@Autowired注解的构造函数对象
if (ann != null) {
//如果先遍历的构造函数对象存在required=ture的属性,则遍历到当前有@Autowired注解构造函数的对象时,
//就会出现异常
if (requiredConstructor != null) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructor: " + candidate +
". Found constructor with 'required' Autowired annotation already: " +
requiredConstructor);
}
//获取@Autowired注解的required属性
boolean required = determineRequiredStatus(ann);
//如果之前存在了候选的@Autowired注解的构造函数对象,则如果当前的候选的构造函数对象中存在
//required=ture的属性则会出现异常
if (required) {
if (!candidates.isEmpty()) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructors: " + candidates +
". Found constructor with 'required' Autowired annotation: " +
candidate);
}
//赋值用来实例化的目标构造函数 ;
requiredConstructor = candidate;
}
//加入到候选的构造函数集合中
candidates.add(candidate);
}
//把无参构造函数暂时赋值默认的候选对象
else if (candidate.getParameterCount() == 0) {
defaultConstructor = candidate;
}
}
//如果候选的构造器对象集合有值;也就是存在有@Autowired注解的构造函数对象,不管required是true还是fales
if (!candidates.isEmpty()) {
// Add default constructor to list of optional constructors, as fallback.
//这一步表示候选的构造函数对象上@Autowired注解中不存在equired=true构造函数对象
//则会把没有@Autowired注解的最后一个构造函数加到候选的集合中
if (requiredConstructor == null) {
//如果存在没有加@Autowired注解的无参构造函数对象,则也会加入到候选的构造函数对象中
if (defaultConstructor != null) {
candidates.add(defaultConstructor);
}
else if (candidates.size() == 1 && logger.isInfoEnabled()) {
logger.info("Inconsistent constructor declaration on bean with name '" + beanName +
"': single autowire-marked constructor flagged as optional - " +
"this constructor is effectively required since there is no " +
"default constructor to fall back to: " + candidates.get(0));
}
}
//赋值候选的构造器对象
candidateConstructors = candidates.toArray(new Constructor<?>[0]);
}
//以下所有的if else判断都是在没有@Autowired注解的条件下进行的
//如果不存在@Autowired注解的构造器对象:并且只有一个有参的构造器,则把这个唯一的有参构造器对象作为候选的构造器
else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
}
//如何存在两个构造函数 存在首选的构造函数,存在没有@Autowired注解的构造器对象 ,并且首选的构造函数不等于没有@Autowired注解的构造器对象
else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};
}
//如果只有一个非合成的构造函数对象那个,并且存在首选的构造函数,说明就只有一个构造函数对象
else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
candidateConstructors = new Constructor<?>[] {primaryConstructor};
}
//最后没有任何一个候选的构造函数
else {
candidateConstructors = new Constructor<?>[0];
}
//把这些候选的构造函数加入到缓存中,方便对多例bean的对象创建
this.candidateConstructorsCache.put(beanClass, candidateConstructors);
}
}
}
//返回找到的候选的构造函数对象
return (candidateConstructors.length > 0 ? candidateConstructors : null);
}
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
@Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
//创建一个bean的封装对象
BeanWrapperImpl bw = new BeanWrapperImpl();
//设置BeanWrapperImpl对象的ConversionService对象转换器和PropertyEditor属性资源编辑器;
//这两个对对象进行操作的工具对象是可以自己进行扩展的,
this.beanFactory.initBeanWrapper(bw);
//定义当前bean使用的构造器对象的变量
Constructor<?> constructorToUse = null;
//定义封装构造器参数的对象
ArgumentsHolder argsHolderToUse = null;
//定义构造器使用的参数对象数组
Object[] argsToUse = null;
//如果传入的构造器参数不为空,则就是指定使用哪一个构造函数进行实例化
if (explicitArgs != null) {
argsToUse = explicitArgs;
}
//如果没有指定实例化的构造函数参数,则需要自己获取
else {
//定义当前的使用的构造函数的参数对象数组
Object[] argsToResolve = null;
//给当前bean定义加锁
synchronized (mbd.constructorArgumentLock) {
//获取实例化的构造函数对象的缓存
constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
//缓存不为null并且使用有参构造函数进行实例化的
if (constructorToUse != null && mbd.constructorArgumentsResolved) {
// Found a cached constructor...
//获取缓存的使用的构造参数对象缓存
argsToUse = mbd.resolvedConstructorArguments;
if (argsToUse == null) {
//如果argsToUse为空,则使用准备好未解析过的的参数对象,因为如果这个参数列表被使用过,则resolvedConstructorArguments是肯定有值的
argsToResolve = mbd.preparedConstructorArguments;
}
}
}
//如果使用bean定义中缓存的未使用过的参数列表,则需要进行参数的解析
if (argsToResolve != null) {
//因为未解析的参数列表中可能存在原始的值,需要根据构造函数相对应的参数类型进行转换,比如把"1" 转成 int类型,但是这个时候可能存在
//循环依赖的问题,因为这是如果两个对象都是构造函数进行依赖的,这时候还不能暴露早期对象
argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
}
}
//如果当前bean不存在缓存的构造函数 或者参数值列表为null,则需要自己获取
//如果有其中一个都能找到对应的构造函数
if (constructorToUse == null || argsToUse == null) {
// Take specified constructors, if any.
//赋值候选的构造器对象
Constructor<?>[] candidates = chosenCtors;
//如果候选的构造器对象数组为null,则需要自己利用class对象进行获取所有的构造器
if (candidates == null) {
//获取class对象
Class<?> beanClass = mbd.getBeanClass();
try {
//获取public修饰的构造函数对象数组
candidates = (mbd.isNonPublicAccessAllowed() ?
beanClass.getDeclaredConstructors() : beanClass.getConstructors());
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Resolution of declared constructors on bean Class [" + beanClass.getName() +
"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
}
}
//如果构造器只有一个 并且传入的构造器参数对象为null 并且没有当前bean定义没有构造器参数
if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
//获取唯一的构造器对象
Constructor<?> uniqueCandidate = candidates[0];
//如果是无参构造器
if (uniqueCandidate.getParameterCount() == 0) {
synchronized (mbd.constructorArgumentLock) {
//给bean定义缓存用来实例化的构造器对象
mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
//标识是通过构造器进行实例化
mbd.constructorArgumentsResolved = true;
//赋值一个空数组对象
mbd.resolvedConstructorArguments = EMPTY_ARGS;
}
//利用反射进行实例化然后赋值给bean的包装对象
//实例化的传参为beanName bean定义 唯一的构造函数对象 空的构造函数参数列表数组
bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
//返回
return bw;
}
}
// Need to resolve the constructor.
//如果传入的候选的构造器数组对象不为null 或者 使用构造器注入模式实例化对象 ;说明需要解析构造器并实例化
boolean autowiring = (chosenCtors != null ||
mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
//定义一个构造器参数封装对象
ConstructorArgumentValues resolvedValues = null;
int minNrOfArgs;
//如果getBean传进来的构造器参不为位空
if (explicitArgs != null) {
//把构造器的参数长度赋值给minNrOfArgs
minNrOfArgs = explicitArgs.length;
}
else {
//获取bean定义的constructorArgumentValues属性值,第一次获取的时候这个是个没有属性值的对象
ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
resolvedValues = new ConstructorArgumentValues();
//解析构造函数的参数个数,如果是第一次解析这个carg中记录的构造器参数的值为0
minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
}
//排序候选的
AutowireUtils.sortConstructors(candidates);
int minTypeDiffWeight = Integer.MAX_VALUE;
Set<Constructor<?>> ambiguousConstructors = null;
LinkedList<UnsatisfiedDependencyException> causes = null;
//遍历候选的构造器对象
for (Constructor<?> candidate : candidates) {
//获取当前构造器的参数个数
int parameterCount = candidate.getParameterCount();
//在这里在进行判断一下:如果指定实例化的构造器对象不为null 构造器参数列表不为null 当前参数列表对象的个数大于当前构造函数参数的个数
//但是constructorToUse ==null || argsToUse == null才会进入此处
if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) {
// Already found greedy constructor that can be satisfied ->
// do not look any further, there are only less greedy constructors left.
break;
}
//当前构造器参数的长度<bean定义中解析出来的参数的长度 ,那么当前构造器一定是不匹配
//如果大于解析出来的参数,可能是匹配的,因为当第一次利用Bean定义实例化时minNrOfArgs=0
if (parameterCount < minNrOfArgs) {
continue;
}
//定义一个封装参数列表的对象
ArgumentsHolder argsHolder;
//获取当前构造函数的参数类型数组
Class<?>[] paramTypes = candidate.getParameterTypes();
//如果getBean传进来的构造器参数为空,就会进入此判断;
if (resolvedValues != null) {
try {
//根据@ConstructorProperties注解获取构造器参数的名称
String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
//如果没有此注解
if (paramNames == null) {
//获取容器中的参数名称发现起
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
if (pnd != null) {
//根据构造函数对象获取参数名称数组
paramNames = pnd.getParameterNames(candidate);
}
}
//主要根据构造器对象获取参数持有对象,从构造器对象中可以获取参数列表的值
//根据走到这一步,说明有多个候选的构造函数参数,也就是
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
}
catch (UnsatisfiedDependencyException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
}
// Swallow and try next constructor.
if (causes == null) {
causes = new LinkedList<>();
}
causes.add(ex);
continue;
}
}
else {
// Explicit arguments given -> arguments length must match exactly.
//如果进入这里,则说明调用getBean时,传入mbd此参数等于null ;但是传入的chosenCtors候选的构造器数组对象有值
//匹配当前候选的构造器对象的参数个数是否等于传入的构造器参数列表个数
if (parameterCount != explicitArgs.length) {
continue;
}
//如果当前的构造器参数个数等于传入的参数列表参数个数,则创建一个参数持有者对象
argsHolder = new ArgumentsHolder(explicitArgs);
}
// isLenientConstructorResolution 判断解析构造函数的时候是否以宽松模式还是严格模式
// 严格模式:解析构造函数时,必须所有的都需要匹配,否则抛出异常
// 宽松模式:使用具有"最接近的模式"进行匹配
// typeDiffWeight:类型差异权重
int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
// Choose this constructor if it represents the closest match.
// 如果它代表着当前最接近的匹配则选择其作为构造函数
//typeDiffWeight值越小越匹配:有个疑问:这个argsHolder是当前候选的构造函数参数持有对象,paramTypes是当前构造函数的
//参数类型数组,是不是当前参数类型和其参数值越匹配就选择其作为实例化的构造函数对象
//每一个构造函数的参数类型和其参数值相匹配找出最匹配的:但是发现用两个有参的@Autowired注解的构造函数,在实例化对象是会报错,都不获
//进入此方法;暂时不知道什么情况下可以传入多个候选的构造函数对象
if (typeDiffWeight < minTypeDiffWeight) {
constructorToUse = candidate;
argsHolderToUse = argsHolder;
argsToUse = argsHolder.arguments;
minTypeDiffWeight = typeDiffWeight;
ambiguousConstructors = null;
}
else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
if (ambiguousConstructors == null) {
ambiguousConstructors = new LinkedHashSet<>();
ambiguousConstructors.add(constructorToUse);
}
ambiguousConstructors.add(candidate);
}
}
if (constructorToUse == null) {
if (causes != null) {
UnsatisfiedDependencyException ex = causes.removeLast();
for (Exception cause : causes) {
this.beanFactory.onSuppressedException(cause);
}
throw ex;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Could not resolve matching constructor " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
}
else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Ambiguous constructor matches found in bean '" + beanName + "' " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
ambiguousConstructors);
}
if (explicitArgs == null && argsHolderToUse != null) {
argsHolderToUse.storeCache(mbd, constructorToUse);
}
}
Assert.state(argsToUse != null, "Unresolved constructor arguments");
//上面代码已经推断出使用的构造函数对象和其参数列表的值,下面就是利用反射技术进行实例化,并且赋值给包装对象
bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
return bw;
}
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
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.
//这一步是执行InstantiationAwareBeanPostProcessor后置处理器的postProcessAfterInstantiation(Object bean, String beanName)方法
//实例化之后属性赋值之前进行的;如果返回false则后面就不会执行自己的属性赋值逻辑
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
//获取bean定义中的属性对象
//这个记录了属性的name和value
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
//获取bean的注入模型
//AUTOWIRE_BY_NAME根据名称进行注入 AUTOWIRE_BY_TYPE根据类型进行注入
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
//把PropertyValues转成MutablePropertyValues
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
//根据bean的名字进行注入
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
//根据类型进行注入
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
//是否有InstantiationAwareBeanPostProcessors后置处理器
//这里又是一种后置处理,用于在 Spring 填充属性到 bean 对象前,对属性的值进行相应的处理,
// * 比如可以修改某些属性的值。
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
//判断是否需要检查依赖
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
//如果有InstantiationAwareBeanPostProcessors后置处理器
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//这一步可以修改属性对象,属性注入之前到bean之前可以修改注入的值
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) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
//执行回调方法 BeanNameAware BeanClassLoaderAware BeanFactoryAware
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
//bean定义不是合成的,一般都是满足 这个条件的
if (mbd == null || !mbd.isSynthetic()) {
//执行BeanPostProcessor后置处理器的Object postProcessBeforeInitialization(Object bean, String beanName)方法
//这一步是在初始化的阶段创建返回一个代理对象
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//执行实现InitializingBean的afterPropertiesSet()方法 和自定义的初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
//执行BeanPostProcessor后置处理器接口的postProcessAfterInitialization;返回一个默认返回入参的对象,可以返回代理对象
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}