Java詳細講解依賴注入的方式
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.是否進行循環(huán)依賴檢測
- Field Injection:不檢測
- Constructor Injection:自動檢測
- Setter Injection:不檢測
可能遇到的問題
循環(huán)依賴報錯: 當服務(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)造方式注入,能夠精準的提醒你是哪兩個類產(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詳細講解依賴注入的方式的詳細內(nèi)容,更多關(guān)于Java依賴注入的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringBoot常用計量與bean屬性校驗和進制數(shù)據(jù)轉(zhuǎn)換規(guī)則全面分析
這篇文章主要介紹了SpringBoot常用計量、bean屬性校驗與進制數(shù)據(jù)轉(zhuǎn)換規(guī)則,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-10-10spring security實現(xiàn)下次自動登錄功能過程解析
這篇文章主要介紹了spring security實現(xiàn)記住我下次自動登錄功能,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11SpringBoot Mybatis動態(tài)數(shù)據(jù)源切換方案實現(xiàn)過程
這篇文章主要介紹了SpringBoot+Mybatis實現(xiàn)動態(tài)數(shù)據(jù)源切換方案過程,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04java.lang.String和java.util.NClob互相轉(zhuǎn)換方式
這篇文章主要介紹了java.lang.String和java.util.NClob互相轉(zhuǎn)換方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09mybatis插件優(yōu)雅實現(xiàn)字段加密的示例代碼
在很多時候,我們都需要字段加密,比如郵箱,密碼,電話號碼等,本文主要介紹了mybatis插件優(yōu)雅實現(xiàn)字段加密的示例代碼,感興趣的可以了解一下2023-11-11關(guān)于JAVA經(jīng)典算法40題(超實用版)
本篇文章小編為大家介紹一下,關(guān)于JAVA經(jīng)典算法40題(超實用版),有需要的朋友可以參考一下2013-04-04