编程语言
首页 > 编程语言> > Spring源码分析第二弹 - DI 依赖注入分析

Spring源码分析第二弹 - DI 依赖注入分析

作者:互联网

上篇说到已经将解析好的bean包装成BeanDefinitionHold 注册到IOC容器了,但保存的bean还没有被实例化,所有不能直接使用。这篇文章我们继续探索

DI依赖注入

1 预准备

HelloService.class //接口
HelloSeriveImpl.class //hello的实现类

@RestController
public class HelloAction {

    @Autowired
    HelloService helloService;

    @RequestMapping("/")
    public String hello(){
        return helloService.hello();
    }
}

2 DI时序图

DI时序图

3.源码分析

public void preInstantiateSingletons() throws BeansException {
	if (logger.isTraceEnabled()) {
		logger.trace("Pre-instantiating singletons in " + this);
	}

	//在上篇文章的DefaultListableBeanFactory#registerBeanDefinition中我们看到已经将所有的beanName添加到这个List<String> beanDefinitionName 这个里面了
	List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

	// Trigger initialization of all non-lazy singleton beans...
	for (String beanName : beanNames) {
		//获取保存在beanDefinitionMap中的Class信息的封装类BeanDefinition
		//上篇文章结尾有说明
		//并用RootBeanDefinition 封装
		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
		//不是抽象类 && 是单例 && 不是延迟加载的
		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
			//是工厂bean 加个&的前缀然后调用getBean
			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 {
				//普通的类之间调用getBean 接下来走这里
				getBean(beanName);
			}
		}
	}

	// Trigger post-initialization callback for all applicable beans...
	//当所有的单例bean初始化完成后
	//实现了SmartInitializingSingleton接口的,在这里回调该接口的 afterSingletonsInstantiated()方法
	for (String beanName : beanNames) {
		Object singletonInstance = getSingleton(beanName);
		if (singletonInstance instanceof SmartInitializingSingleton) {
			StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
					.tag("beanName", beanName);
			SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
			if (System.getSecurityManager() != null) {
				AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
					smartSingleton.afterSingletonsInstantiated();
					return null;
				}, getAccessControlContext());
			}
			else {
				smartSingleton.afterSingletonsInstantiated();
			}
			smartInitialize.end();
		}
	}
}

3.1 初始化阶段

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("xxx.xml");
ctx.getBean("beanName") - > AbstractBeanFactory.doGetBean() //向IoC容器获取被管理Bean的过程
//重点关注这段 创建单例
if (mbd.isSingleton()) {
	//先从缓存获取实例对象 先看这个方法
    sharedInstance = getSingleton(beanName, () -> {
        try {
            //接下来走这个方法
            return createBean(beanName, mbd, args);
        }
        catch (BeansException ex) {
            destroySingleton(beanName);
            throw ex;
        }
    });
    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
	Assert.notNull(beanName, "Bean name must not be null");
	synchronized (this.singletonObjects) {
		//从单例缓存map中取
		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 + "'");
			}
			//没取到缓存 实例化bean之前的回调
			beforeSingletonCreation(beanName);
			boolean newSingleton = false;
			boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
			if (recordSuppressedExceptions) {
				this.suppressedExceptions = new LinkedHashSet<>();
			}
			try {
				//传入的回调 AbstractBeanFactory#createBean
				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) {
				//保存到缓存map
				addSingleton(beanName, singletonObject);
			}
		}
		return singletonObject;
	}
}
//单例的 加锁保证安全
protected void addSingleton(String beanName, Object singletonObject) {
	synchronized (this.singletonObjects) {
		this.singletonObjects.put(beanName, singletonObject);
		this.singletonFactories.remove(beanName);
		this.earlySingletonObjects.remove(beanName);
		this.registeredSingletons.add(beanName);
	}
}

//singletonObjects
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
    	//对beanDefinition 的封装
		RootBeanDefinition mbdToUse = mbd;

		......
            
        //多余的代码去掉了 重点关注这里
		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) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
		}
	}

//接下来到Bean创建
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
		throws BeanCreationException {
	
	// Instantiate the bean. 最终保存bean实例化对象的封装
	BeanWrapper instanceWrapper = null;
	if (mbd.isSingleton()) {
	   	//如果当前bean是工厂bean,已经实例化的话则直接取出来并删除
		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
	}
	if (instanceWrapper == null) {
		//我们自己手写的bean,应该都是走这里
	    //重点关注点 一般来说spring除了加了lazy配置 一般都会走这个
		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 {
	            //单例缓存标识
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
			}
			catch (Throwable ex) {
				throw new BeanCreationException(mbd.getResourceDescription(), beanName,
						"Post-processing of merged bean definition failed", ex);
			}
			mbd.postProcessed = true;
		}
	}
	
	// Initialize the bean instance.
	Object exposedObject = bean;
	try {
	    //依赖注入 也是重点关注
		populateBean(beanName, mbd, instanceWrapper);
	    //bean的初始化 aop切面的入口
		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);
		}
	}
	  
	//不需要关注的代码暂时去掉
	return exposedObject;
}
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
   	//检查确认Bean是初始化的 如果这个方法跟到最后能看到这样一行代码
   	//return (clToUse != null ? clToUse.loadClass(name) : Class.forName(name));
	Class<?> beanClass = resolveBeanClass(mbd, beanName);

	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());
	}

	Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
	if (instanceSupplier != null) {
		return obtainFromSupplier(instanceSupplier, beanName);
	}

	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);
		}
	}

	// 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);
}


//无参构造方法初始化对象
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
	try {
		Object beanInstance;
		final BeanFactory parent = this;
		//获取系统的安全管理接口,JDK标准的安全管理API
		if (System.getSecurityManager() != null) {
			//这里是一个匿名内置类,根据初始化策略创建初始化对象
			beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
					getInstantiationStrategy().instantiate(mbd, beanName, parent),
					getAccessControlContext());
		}
		else {
			//获得初始化对象
			beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
		}
        //将初始化的对象封装起来 这里拿到beanInstance了 初始化阶段到此结束
        //封装返回一个BeanWrapper
		BeanWrapper bw = new BeanWrapperImpl(beanInstance);
		initBeanWrapper(bw);
		return bw;
	}
	catch (Throwable ex) {
		throw new BeanCreationException(
				mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
	}
}
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
	// Don't override the class with CGLIB if no overrides.
	//如果Bean定义中没有方法覆盖,则就不需要CGLIB父类类的方法
	if (!bd.hasMethodOverrides()) {
		Constructor<?> constructorToUse;
		synchronized (bd.constructorArgumentLock) {
			//获取对象的构造方法或工厂方法
			constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
			//如果没有构造方法且没有工厂方法
			if (constructorToUse == null) {
				//使用JDK的反射机制,判断要初始化的Bean是否是接口
				final Class<?> clazz = bd.getBeanClass();
				if (clazz.isInterface()) {
					throw new BeanInstantiationException(clazz, "Specified class is an interface");
				}
				try {
					if (System.getSecurityManager() != null) {
						//这里是一个匿名内置类,使用反射机制获取Bean的构造方法
						constructorToUse = AccessController.doPrivileged(
								(PrivilegedExceptionAction<Constructor<?>>) () -> clazz.getDeclaredConstructor());
					}
					else {
						constructorToUse =	clazz.getDeclaredConstructor();
					}
					bd.resolvedConstructorOrFactoryMethod = constructorToUse;
				}
				catch (Throwable ex) {
					throw new BeanInstantiationException(clazz, "No default constructor found", ex);
				}
			}
		}
		//使用BeanUtils初始化,通过反射机制调用”构造方法.newInstance(arg)”来进行初始化
        //至此bean已经被初始化了
		return BeanUtils.instantiateClass(constructorToUse);
	}
	else {
		// Must generate CGLIB subclass.
		//使用CGLIB来初始化对象
		return instantiateWithMethodIjection(bd, beanName, owner);
	}
}

至此,class类已经初始化完成。接下来我们看怎么注入的

3.2 注入阶段

//找到这里
Object exposedObject = bean;
try {
    //将Bean初始对象封装,并对依赖的变量和依赖的其他类赋值
    //主要看这个  依赖注入 前面有提到过
    populateBean(beanName, mbd, instanceWrapper);
    //初始化Bean对象的初始方法 aop切面的入口aop讲解 在下篇AOP里面分析
    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进行属性注入
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
  			.....
       //获取所有属性        
   	PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
   int resolvedAutowireMode = mbd.getResolvedAutowireMode();
   //自动装配
	if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
		// Add property values based on autowire by name if applicable.
		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;
	}

	boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();

	//是否需要检查依赖
    boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
	PropertyDescriptor[] filteredPds = null;
	if (hasInstAwareBpps) {
		if (pvs == null) {
			pvs = mbd.getPropertyValues();
		}
		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);
					}
                       //!!! @Autowrite 注解形式的注入 我们重点看这里! 
                       //不要问为什么走这里 断点跟到这里的
                       //走这个类 AutowiredAnnotationBeanPostProcessor
					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);
	}
}
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
      //注入关系获取
	InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
	try {
          //进行注入
		metadata.inject(bean, beanName, pvs);
	}
	......
	return pvs;
}
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
	Field field = (Field) this.member;
	Object value;
	if (this.cached) {
		try {
			//实例化依赖的bean,该方法下面有用反射注入 我们接下来看这个  
			value = resolvedCachedArgument(beanName, this.cachedFieldValue);
		}
		catch (NoSuchBeanDefinitionException ex) {
			// Unexpected removal of target bean for cached argument -> re-resolve
			value = resolveFieldValue(field, bean, beanName);
		}
	}
	else {
		value = resolveFieldValue(field, bean, beanName);
	}
	//如果依赖的对象不为空 用反射设值
	if (value != null) {
		ReflectionUtils.makeAccessible(field);
		field.set(bean, value);
	}
}


@Nullable
private Object resolvedCachedArgument(@Nullable String beanName, @Nullable Object cachedArgument) {
	if (cachedArgument instanceof DependencyDescriptor) {
		DependencyDescriptor descriptor = (DependencyDescriptor) cachedArgument;
		Assert.state(this.beanFactory != null, "No BeanFactory available");
		//这里的beanFactory还记得吧 DefaultListableBeanFactory
		return this.beanFactory.resolveDependency(descriptor, beanName, null, null);
	}
	else {
		return cachedArgument;
	}
}
// doResolveDependency 下找到这里
//如果是Class
if (instanceCandidate instanceof Class) {
    //DependencyDescriptor.resolveCandidate
	instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
}

//DependencyDescriptor#resolveCandidate
//接下来就能看到神奇的一幕了
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory)
	throws BeansException {
	//getBean !!!
	return beanFactory.getBean(beanName);
}
	//beanName -> 工厂类的封装 BeanWrapper
	private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>();
//applicationContext中的顶级接口BeanFactory中的方法
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
//实现类在AbstractApplicationContext类中
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
	assertBeanFactoryActive();
	return getBeanFactory().getType(name);
}

//接下来到AbstractBeanFactory#getType 记住第二个参数allowFactoryBeanInit
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
	return getType(name, true);
}
public Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException {
	//获取beanName
	String beanName = transformedBeanName(name);

	// Check manually registered singletons.
	//是否已经存在单例缓存map中了singletonObjects
	Object beanInstance = getSingleton(beanName, false);
	//Nullbean.class的
	if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
		if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
			return getTypeForFactoryBean((FactoryBean<?>) beanInstance);
		}
		else {
			return beanInstance.getClass();
		}
	}

	// No singleton instance found -> check bean definition.
	BeanFactory parentBeanFactory = getParentBeanFactory();
	//没有被容器扫描到的
	if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
		// No bean definition found in this factory -> delegate to parent.
		return parentBeanFactory.getType(originalBeanName(name));
	}

	RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

	// Check decorated bean definition, if any: We assume it'll be easier
	// to determine the decorated bean's type than the proxy's type.
	BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
	//beanName是不是以 ‘&’ 开头的
	if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
		RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
		Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);
		if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
			return targetClass;
		}
	}

	Class<?> beanClass = predictBeanType(beanName, mbd);

	// Check bean class whether we're dealing with a FactoryBean.
	//最后判断是否是实现了FactoryBean的 但是不是&开头的
	if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {
		if (!BeanFactoryUtils.isFactoryDereference(name)) {
			// If it's a FactoryBean, we want to look at what it creates, not at the factory class.
			//接下来走这里 
			return getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit).resolve();
		}
		else {
			return beanClass;
		}
	}
	else {
		return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null);
	}
}
//找到这段代码 还记得前面第二个参数吧 传的true
if (allowInit) {
	FactoryBean<?> factoryBean = (mbd.isSingleton() ?
			//如果是单例就走这里
			getSingletonFactoryBeanForTypeCheck(beanName, mbd) :
			getNonSingletonFactoryBeanForTypeCheck(beanName, mbd));
	if (factoryBean != null) {
		// Try to obtain the FactoryBean's object type from this early stage of the instance.
		Class<?> type = getTypeForFactoryBean(factoryBean);
		if (type != null) {
			return ResolvableType.forClass(type);
		}
		// No type found for shortcut FactoryBean instance:
		// fall back to full creation of the FactoryBean instance.
		return super.getTypeForFactoryBean(beanName, mbd, true);
	}
}
private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
	synchronized (getSingletonMutex()) {
		//从缓存map中取到了就直接返回
		BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
		if (bw != null) {
			return (FactoryBean<?>) bw.getWrappedInstance();
		}
		//从单例map中取到就返回 
		//取值时是factoryBeanInstanceCache优先于singletonObjects map
		//初始化时是singletonObjects map优先于factoryBeanInstanceCache
		//最终会保存到singletonObjects map
		Object beanInstance = getSingleton(beanName, false);
		if (beanInstance instanceof FactoryBean) {
			return (FactoryBean<?>) beanInstance;
		}
		if (isSingletonCurrentlyInCreation(beanName) ||
				(mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) {
			return null;
		}

		Object instance;
		try {
			//创建单例前的回调
			beforeSingletonCreation(beanName);
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			instance = resolveBeforeInstantiation(beanName, mbd);
			if (instance == null) {
				//创建一个实例化对象
				bw = createBeanInstance(beanName, mbd, null);
				instance = bw.getWrappedInstance();
			}
		}
		catch (UnsatisfiedDependencyException ex) {
			// Don't swallow, probably misconfiguration...
			throw ex;
		}
		catch (BeanCreationException ex) {
			// Don't swallow a linkage error since it contains a full stacktrace on
			// first occurrence... and just a plain NoClassDefFoundError afterwards.
			if (ex.contains(LinkageError.class)) {
				throw ex;
			}
			// Instantiation failure, maybe too early...
			if (logger.isDebugEnabled()) {
				logger.debug("Bean creation exception on singleton FactoryBean type check: " + ex);
			}
			onSuppressedException(ex);
			return null;
		}
		finally {
			// Finished partial creation of this bean.
			//完成实例化后的回调
			afterSingletonCreation(beanName);
		}

		FactoryBean<?> fb = getFactoryBean(beanName, instance);
		if (bw != null) {
			//保存到BeanWrapper缓存map中
			this.factoryBeanInstanceCache.put(beanName, bw);
		}
		return fb;
	}
}

4 本文中的比较关注的成员变量

	//保存beanName的list 可以用此beanName取出对应的class BeanDefinition信息
	private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
	//beanName -> BeanWrapper对象
	private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>();
	//beanName -> 实例化对象
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

5 DI依赖注入总结

  1. AbstractApplicationContext##refresh()下的finishBeanFactoryInitialization()#beanFactory.preInstantiateSingletons()中通过遍历beanDefinitionNames调用getBean()实例化对象,让代码解耦统一走getBean()更加的规范,完美解决循环依赖(程序初始化遍历一次,自己调用一次)
  2. 从上面代码看到依赖注入就如同递归,A依赖B,B依赖C,加载A的时候会去实例化B,实例化B的时候会去实例化C,直到最后没有依赖才算完结
  3. 通过Filed反射调用的方式进行注入

注入有没有你想象的那么高级? 哈哈,反正我一开始是没想到会是这种方式的。
下篇分析AOP切面源码,分析前一定要先看懂动态代理

以上就是本章的全部内容了。

上一篇:Spring源码分析第一弹 - IOC控制反转
下一篇:Spring源码分析第三弹 - AOP切面编程分析

云想衣裳花想容,春风拂槛露华浓

标签:return,DI,mbd,Spring,beanName,bean,源码,ex,null
来源: https://blog.csdn.net/qq_35551875/article/details/121810283