先对UserService的test方法进行切面,然后再对test方法进行@Async,在存在循环依赖的情况下,启动项目会报错
@Service
public class OrderService {
@Autowired
private UserService userService;
}
@Service
public class UserService {
@Autowired
private OrderService orderService;
@Async
public void test(){
System.out.println("test");
}
}
@ComponentScan(basePackages = "com.test.zh")
@EnableAspectJAutoProxy
@EnableAsync
public class SpringConfig {
}
@Aspect
@Component
public class TestAspect {
@Pointcut("execution(* com.test.zh.*..*(..))")
public void log(){
}
@Before("log()")
public void test(JoinPoint joinPoint) {
System.out.println("before aspect");
}
}
//AbstractAutowireCapableBeanFactory
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
Object exposedObject = bean;
try {
//依赖注入,循环依赖发生在这里,如果有循环依赖,则提前进行AOP
//并将代理对象放入二级缓存
this.populateBean(beanName, mbd, instanceWrapper);
//在这里进行初始化后的操作,如果已经进行过切面代理,则直接将原对象返回
//但是方法如果被@Async修饰,则会直接创建代理对象,并将代理对象返回,所以这里返回的是代理对象,导致后面exposedObject != bean
exposedObject = this.initializeBean(beanName, exposedObject, mbd);
} catch (Throwable var18) {
if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
throw (BeanCreationException)var18;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var18);
}
if (earlySingletonExposure) {
//如果已经进行过AOP,则从二级缓存中将代理对象返回
Object earlySingletonReference = this.getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
} else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
String[] dependentBeans = this.getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length);
String[] var12 = dependentBeans;
int var13 = dependentBeans.length;
for(int var14 = 0; var14 < var13; ++var14) {
String dependentBean = var12[var14];
if (!this.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.");
}
}
}
}
//AbstractAutowireCapableBeanFactory
@Override
//依次进行初始化后操作
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
//先进行AspectJ的切面操作,AspectJ的切面操作,如果发现已经执行过代理,则将原对象返回
//然后进行Async的切面操作,这里不会判断原对象是否经过代理,而是直接生成代理对象,将代理对象返回
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
//AbstractAutoProxyCreator#postProcessAfterInitialization
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
//如果已经进行过AOP,则直接将原对象返回
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
原因总结
当被方法被@Async修饰,这个类会被代理,而且会直接生成代理对象,导致在doCreateBean中,判断的时候,exposedObject和bean不再相等。
解决办法
发生循环依赖的依赖注入上,加上@Lazy
@Service
public class UserService {
@Autowired
@Lazy
private OrderService orderService;
@Async
public void test(){
System.out.println(orderService);
}
}
原理
当在依赖注入上加上@Lazy时,注入这个属性时,就不会去容器中查找对象是否存在,而是直接生成这个属性的代理对象。直到调用test方法时,打印orderService需要调用OrderService的toString方法,此时才会去容器中查找是否有orderService的普通对象,如果沒有,则进行创建。但是此时UserService对象已经创建好了,放入单例池中了,所以就不存在循环依赖了,创建OrderService对象时,UserService对象可以直接注入。