[Spring] 添加@Async注解,導(dǎo)致spring啟動失敗[轉(zhuǎn)載記錄]

前言

這篇文章里,最后總結(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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容