报错信息:
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'A': Bean with name 'A' has been injected into other beans [B] 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.
类A
@Component
public class A {
@Autowired
private B b;
public void test01(){
System.out.println("我是A中test01方法");
}
}
@Component
public class B {
@Autowired
private A a;
@Async
public void test01(){
System.out.println("我是B中test01方法");
}
}
以下是spring.xml部分配置
<!-- 开启自动切面代理 aop 指定的是aspectj -->
<aop:aspectj-autoproxy/>
<!-- 定时器和线程开关 默认代理是 mode="proxy" -->
<task:annotation-driven />
如果aop:aspectj-autoproxy/ 配置的是aspectj动态代理,那么 <task:annotation-driven /> 没有指定为aspectj 默认代理为JDK 就会报This means that said other beans do not use the final version of the bean,因为两个代理都代理了B中的test01,导致多个version , 在doCreateBean 中就会抛出此异常。表示这个bean有多个版本。
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 " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
解决方案:
1.使用@Lazy
@Component
public class A {
@Autowired
@Lazy
private B b;
public void test01(){
System.out.println("我是A中test01方法");
}
}
注:要在被注入的全局属性上加@Lazy才会生效
2.调整spring配置文件.使用同一种动态代理
<!-- 开启自动切面代理 aop 指定的是aspectj -->
<aop:aspectj-autoproxy/>
<!-- 定时器和线程开关 默认代理是 mode="aspectj" -->
<task:annotation-driven />