在这篇文章里,最后总结处,我说了会讲讲循环依赖中,其中一个类添加@Async有可能会导致注入失败而抛异常的情况,今天就分析一下。
@Service
public class CycleService1 {
@Autowired
private CycleService2 cycleService2;
@WangAnno
@Async
public void doThings() {
System.out.println("it's a async move");
}
}
@Service
public class CycleService2 {
private CycleService1 cycleService1;
public void init() {
}
@WangAnno
public void alsoDo() {
System.out.println("create cycleService2");
}
}
Bean with name ‘cycleService1’ has been injected into other beans [cycleService2] 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.
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'cycleService1': Bean with name 'cycleService1' has been injected into other beans [cycleService2] 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.
Exception in thread "main" org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'cycleService1': Bean with name 'cycleService1' has been injected into other beans [cycleService2] 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.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:654)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:523)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:851)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:884)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:552)
at com.wang.Test.main(Test.java:109)
想想我在这篇博客里的图解步骤:
也就是说基于raw bean,得到了两个基于该raw bean生成的proxy对象,Spring容器不知道最终该在容器里保存哪一个了。
if (earlySingletonExposure) {
// 返回一个进行了aop处理的ObjectFactory,提前暴露
// 但是只有当该实例在创建过程中还被其他实例引用(循环依赖),才会被调用getEarlyBeanReference
// 此处是第四次调用beanPostProcessor,不一定会调用,只有当该类真的在创建过程中被其他类当做属性所依赖
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
然后咱们debug发现,只有AbstractAutoProxyCreator#getEarlyBeanReference方法,有具体实现逻辑
public Object getEarlyBeanReference(Object bean, String beanName) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
this.earlyProxyReferences.put(cacheKey, bean);
return wrapIfNecessary(bean, beanName, cacheKey);
}
具体的细节,我们就不进入的,主要就是通过调用wrapIfNecessary生成了raw bean的aop proxy bean,后面放入了二级缓存。
在initializeBean方法里会调用applyBeanPostProcessorsAfterInitialization方法
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
在循环里面会调用postProcessAfterInitialization方法
重点关注AbstractAutoProxyCreator的该方法实现:
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
// 对bean进行proxy操作
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
会发现AbstractAutoProxyCreator#postProcessAfterInitialization里面的具体逻辑就是判断这个类有没有调用过wrapIfNecessary,如果调用过就不再调用,就是保证同一个raw bean不会被多次proxy,同时提前暴露注入到其他对象里的就是proxy bean。
但是由于该bean(CycleService1)上加了@Async注解,此次也会触发AsyncAnnotationBeanPostProcessor#postProcessAfterInitialization,而这个方法,我们在这篇文章里讲过了,正是@Async注解能生效的关键逻辑。所以此处生成了一个具有Async功能的新的async proxy bean
基于2.3和2.4,我们基于raw bean得到了二级缓存里的aop proxy bean和async proxy bean。
让我们再回忆一下判断逻辑:
//此处是从二级缓存里面根据beanName拿出对象,因为二级缓存里放入的是因为循环依赖给其他bean注入的代理对象
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
// 我们之前早期暴露出去的Bean跟现在最后要放到容器中的Bean不是同一个
// allowRawInjectionDespiteWrapping为false
// 并且当前Bean被当成依赖注入到了别的Bean中
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
// 获取到当前Bean依赖的Bean
String[] dependentBeans = getDependentBeans(beanName);
// 要得到真实的依赖的Bean
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.");
}
}
}
简而言之,也就是此时从二级缓存里拿到了aop proxy bean,同时了执行完initializeBean之后,raw bean变为了async proxy bean,Spring容器基于raw bean得到了两个proxy bean,无法处理了。所以在使用@Async注解时,尽量不要在被循环依赖的Class上添加
目前我能想到的方法就是打破循环依赖,因为循环依赖发生在bean生命周期的–属性注入阶段,所以我们需要做的就是打破这种循环依赖
@Service
public class CycleService1 {
@Lazy
@Autowired
private CycleService2 cycleService2;
@WangAnno
@Async
public void doThings() {
cycleService2.alsoDo();
System.out.println("it's a async move");
}
}
看过这篇文章的都知道原理了,此处不再累赘
@Service
public class CycleService1 {
@Autowired
private ApplicationContext applicationContext;
private CycleService2 cycleService2;
@WangAnno
@Async
public void doThings() {
if (Objects.isNull(cycleService2)) {
cycleService2 = applicationContext.getBean(CycleService2.class);
}
cycleService2.alsoDo();
System.out.println("it's a async move");
}
}
其实效果是上面加了@Lazy效果是一样的,不过是我们自己在方法执行的过程中手动进行延迟注入而已。
其实大家仔细分析就会发现,主要问题在于CycleService1先被Spring实例化
@Service
@DependsOn("cycleService2")
public class CycleService1 {
@Autowired
private CycleService2 cycleService2;
@WangAnno
@Async
public void doThings() {
System.out.println("it's a async move");
}
}
和
@Service
public class CycleService2{
@Autowired
private CycleService1 cycleService1;
@WangAnno
public void alsoDo() {
System.out.println("create cycleService2");
}
}
启动运行,也能解决。nice~~~~~
从二级缓存里拿到earlySingletonReference(aop proxy bean),同时了执行完initializeBean之后,raw bean变为了exposedObject(async proxy bean),Spring容器基于raw bean得到了两个proxy bean,无法处理了。
所以在使用@Async注解时,尽量不要在被循环依赖的Class上添加
实在非要添加,可以看看我给出的解决方法。