Java詳細(xì)講解依賴注入的方式
Spring中的三種依賴注入方式
- Field Injection :@Autowired注解的一大使用場景就是Field Injection
- Constructor Injection :構(gòu)造器注入,是我們?nèi)粘W顬橥扑]的一種使用方式Setter Injection:
- Setter Injection也會用到@Autowired注解,但使用方式與Field Injection有所不同,F(xiàn)ield Injection是用在成員變量上,而Setter Injection的時候,是用在成員變量的Setter函數(shù)上
// Field Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl<UploadDao, UploadEntity> implements UploadService {
@Autowired
private UploadDao uploadDao;
}
// Constructor Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl<UploadDao, UploadEntity> implements UploadService {
private UploadDao uploadDao;
UploadServiceImpl(UploadDao uploadDao){
this.uploadDao = uploadDao;
}
}
// Setter Injection
@Service("uploadService")
public class UploadServiceImpl extends ServiceImpl<UploadDao, UploadEntity> implements UploadService {
private UploadDao uploadDao;
@Autowired
public void setUploadDao(UploadDao uploadDao){
this.uploadDao =uploadDao
}
}
1.是否進(jìn)行循環(huán)依賴檢測
- Field Injection:不檢測
- Constructor Injection:自動檢測
- Setter Injection:不檢測
可能遇到的問題
循環(huán)依賴報錯: 當(dāng)服務(wù)A需要用到服務(wù)B時,并且服務(wù)B又需要用到服務(wù)A時,Spring在初始化創(chuàng)建Bean時,不知道應(yīng)該先創(chuàng)建哪一個,就會出現(xiàn)該報錯。
This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example
class ServerA{
@Autowired
private ServerB b;
}
class ServerB{
@Autowired
private ServerA a;
}
如果使用構(gòu)造方式注入,能夠精準(zhǔn)的提醒你是哪兩個類產(chǎn)生了循環(huán)依賴 .異常報錯信息能夠迅速定位問題:

循環(huán)報錯解決辦法是使用 @Lazy注解 ,對任意一個需要被注入Bean添加該注解,表示延遲創(chuàng)建即可。
class ServerA{
@Autowired
@Lazy
private ServerB b;
}
class ServerB{
@Autowired
@Lazy
private ServerA a;
}
以上就是Java詳細(xì)講解依賴注入的方式的詳細(xì)內(nèi)容,更多關(guān)于Java依賴注入的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用Java實(shí)現(xiàn)百萬Excel數(shù)據(jù)導(dǎo)出
這篇文章主要為大家詳細(xì)介紹了如何使用Java實(shí)現(xiàn)百萬Excel數(shù)據(jù)導(dǎo)出,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,有需要的小伙伴可以參考一下2024-03-03
Jackson庫進(jìn)行JSON?序列化時遇到了無限遞歸(Infinite?Recursion)的問題及解決方案
使用Jackson庫進(jìn)行JSON序列化時遇到了無限遞歸(Infinite?Recursion)問題,這是因?yàn)閮蓚€實(shí)體類ComPointQuotaEntity和?ComPointEntity之間存在雙向關(guān)聯(lián)point和pointQuota相互引用,本文給大家介紹解決方案,感興趣的朋友一起看看吧2025-03-03
Java實(shí)現(xiàn)貪吃蛇游戲(1小時學(xué)會)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)貪吃蛇游戲,1小時學(xué)會貪吃蛇游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-05-05
IDEA啟動Tomcat時控制臺出現(xiàn)亂碼問題及解決
這篇文章主要介紹了IDEA啟動Tomcat時控制臺出現(xiàn)亂碼問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
java利用Future實(shí)現(xiàn)多線程執(zhí)行與結(jié)果聚合實(shí)例代碼
這篇文章主要給大家介紹了關(guān)于java利用Future實(shí)現(xiàn)多線程執(zhí)行與結(jié)果聚合的相關(guān)資料,Future模式的核心,去除了主函數(shù)的等待時間,并使得原本需要等待的時間段可以用于處理其他業(yè)務(wù)邏輯,需要的朋友可以參考下2021-12-12
Java實(shí)現(xiàn)MapStruct對象轉(zhuǎn)換的示例代碼
本文主要介紹了MapStruct在Java中的對象轉(zhuǎn)換使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12

