循环依赖-Autowired方式

@Autowired方式

例子

@Component
public class TestA {

    @Autowired
    private TestB testB;
}
@Component
public class TestB {

    @Autowired
    private TestA testA;
}
  • TestA开始,AbstractBeanFactory.doGetBean方法开始分析,getSingleton一级缓存获取beanName,结果null
protected <T> T doGetBean(
			String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
			throws BeansException {

		String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
    // 这是从一级、二级、三级进行获取
		Object sharedInstance = getSingleton(beanName);
		。。。。。
			try {
			。。。。。。。。
				// 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);
				}

				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;
	}
	
  • AbstractBeanFactory的父类DefaultSingletonBeanRegistry getSingleton方法进行三级缓存装配,放入ObjectFactory
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;
						}
					});
  • 之后singletonFactory.getObject()创建bean
/**
	 * Return the (raw) singleton object registered under the given name,
	 * creating and registering a new one if none registered yet.
	 * @param beanName the name of the bean
	 * @param singletonFactory the ObjectFactory to lazily create the singleton
	 * with, if necessary
	 * @return the registered singleton 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) {
        // 。。。。。。
				beforeSingletonCreation(beanName);
				boolean newSingleton = false;
				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;
		}
	}
  • 进入AbstractAutowireCapableBeanFactory createBean方法,resolveBeforeInstantiation调用BeanPostProcessor,进行前置InstantiationAwareBeanPostProcessor,如果InstantiationAwareBeanPostProcessor处理生成代理bean后,进行后置处理【后边在doCreateBean后的initializeBean仍会调用BeanPostProcessor进行前置、后置处理】,然后调用doCreateBean
/**
	 * Central method of this class: creates a bean instance,
	 * populates the bean instance, applies post-processors, etc.
	 * @see #doCreateBean
	 */
	@Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		。。。。。。
		try {
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
		}
		。。。。。。。
		try {
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isTraceEnabled()) {
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
    。。。。。。
	}
  • 进入AbstractAutowireCapableBeanFactory doCreateBean,然后调用createBeanInstance,返回bean后,提前暴露到第三级缓存避免循环依赖问题addSingletonFactory(),放入的是一个BeanFactory,以后会getBean获取,

    protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
       Assert.notNull(singletonFactory, "Singleton factory must not be null");
       synchronized (this.singletonObjects) {
          if (!this.singletonObjects.containsKey(beanName)) {
             this.singletonFactories.put(beanName, singletonFactory);
             this.earlySingletonObjects.remove(beanName);
             this.registeredSingletons.add(beanName);
          }
       }
    }
    

    populateBean()创建依赖的Bean注入,本次是依赖TestB,实例化TestB,过程如下:

    • 调用populateBean()方法

    • AutowiredAnnotationBeanPostProcessor postProcessProperties()注入

    • InjectionMetadata inject()

    • DefaultListableBeanFactory resolveDependency()

    • AbstractBeanFactory doGetBean,重复TestA创建过程,加入第三级singletonFactories缓存,待使用

    • AbstractBeanFactory doGetBean,此时想要获取TestA类,进入到最开始DefaultSingletonBeanRegistry getSingleton()方法

      从三级缓存获取,三级缓存存放的是匿名类,进行类方法调用getEarlyBeanReference(),放入二级缓earlySingletonObjects,移除三级缓存singletonFactories.remove(beanName)

    • 将TestA反射注入TestB中,ReflectionUtils.makeAccessible(field); field.set(bean, value);,AbstractAutowireCapableBeanFactory initializeBean(),前后置处理器处理代理

    • DefaultSingletonBeanRegistrygetSingleton(), TestB放入到一级缓存,清楚二三级TestB缓存

    • 将TestB反射注入TestA中,ReflectionUtils.makeAccessible(field); field.set(bean, value);,AbstractAutowireCapableBeanFactory initializeBean(),前后置处理器处理代理

    • AbstractAutowireCapableBeanFactory调用DefaultSingletonBeanRegistry getSingleton()方法,将TestA放入二级缓存,清除三级缓存

    • DefaultSingletonBeanRegistry addSingleton()加入一级缓存,清除二三级缓存

	protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
			。。。。。。
			instanceWrapper = createBeanInstance(beanName, mbd, args);
      。。。。。。
		Object bean = instanceWrapper.getWrappedInstance();
		。。。。。。
		// 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));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
      // 丰富化,创建依赖的Bean注入
			populateBean(beanName, mbd, instanceWrapper);
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		。。。。。。。
		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<>(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 " +
								"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}
  • 进入AbstractAutowireCapableBeanFactory createBeanInstance,然后调用createBeanInstance,类型判断,是否构造器注入,本次使用Autowired注入,进入instantiateBean方法,反射实例化,返回包装类BeanWrapper bw = new BeanWrapperImpl(beanInstance);
/**
	 * Create a new instance for the specified bean, using an appropriate instantiation strategy:
	 * factory method, constructor autowiring, or simple instantiation.
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @param args explicit arguments to use for constructor or factory method invocation
	 * @return a BeanWrapper for the new instance
	 * @see #obtainFromSupplier
	 * @see #instantiateUsingFactoryMethod
	 * @see #autowireConstructor
	 * @see #instantiateBean
	 */
	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		......

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: @Autowired循环依赖问题是指在使用@Autowired注解进行属性注入时,如果存在循环依赖关系,会导致注入失败。解决循环依赖问题的时机是在Bean的创建过程中。当Spring容器创建Bean时,会先创建Bean的实例,然后再进行属性注入。如果发现存在循环依赖关系,Spring会将正在创建的Bean放入一个缓存中,然后继续创建其他Bean。当其他Bean创建完成后,Spring会再次尝试注入之前缓存的Bean,从而解决循环依赖问题。\[2\] 在使用@Autowired注解时,可以通过setter方法进行注入。首先定义一个成员变量,然后使用@Autowired注解标注setter方法,将需要注入的Bean作为参数传入。这样,在Spring容器创建Bean时,会自动调用setter方法进行注入。\[2\] 另外,循环依赖问题也可以通过使用@Resource注解来解决。@Resource注解默认通过byname的方式实现注入,如果找不到对应的名字,则通过byType实现。如果两种方式都找不到,就会报错。因此,可以使用@Resource注解来解决循环依赖问题。\[1\] 总结起来,循环依赖问题可以通过在Bean的创建过程中解决,使用@Autowired注解的setter方法或@Resource注解来实现属性注入,从而解决循环依赖问题。\[1\]\[2\] #### 引用[.reference_title] - *1* *2* *3* [Spring之Bean自注入问题之@Autowired进来的Bean为null 循环依赖大致处理过程](https://blog.csdn.net/Be_insighted/article/details/121526557)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值