前言
在這篇文章里,最后總結(jié)處,我說了會講講循環(huán)依賴中,其中一個(gè)類添加@Async有可能會導(dǎo)致注入失敗而拋異常的情況,今天就分析一下。
一、異常表現(xiàn),拋出內(nèi)容
1.1 循環(huán)依賴的兩個(gè)class
1. CycleService1
@Service
public class CycleService1 {
@Autowired
private CycleService2 cycleService2;
@WangAnno
@Async
public void doThings() {
System.out.println("it's a async move");
}
}
2. CycleService2
@Service
public class CycleService2 {
private CycleService1 cycleService1;
public void init() {
}
@WangAnno
public void alsoDo() {
System.out.println("create cycleService2");
}
}
1.2 啟動報(bào)錯(cuò)
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.
解決方案
1. 延遲注入(使用@Lazy注解)
@Service
public class CycleService1 {
@Lazy
@Autowired
private CycleService2 cycleService2;
@WangAnno
@Async
public void doThings() {
cycleService2.alsoDo();
System.out.println("it's a async move");
}
}
看過這篇文章的都知道原理了,此處不再累贅
2. 手動延遲注入(使用applicationContext.getBean)
@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");
}
}
其實(shí)效果是上面加了@Lazy效果是一樣的,不過是我們自己在方法執(zhí)行的過程中手動進(jìn)行延遲注入而已。
————————————————
版權(quán)聲明:本文為CSDN博主「liangsheng_g」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/liangsheng_g/article/details/119976614