寫法:
咱們先看官網(wǎng)文檔是怎么的:
The Spring team generally advocates constructor injection as it enables one to implement application components as?immutable objects?and to ensure that required dependencies are not null. Furthermore, constructor-injected components are always returned to client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a?bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later.?
我們把他翻譯出來就是:
Spring團(tuán)隊(duì)通常提倡構(gòu)造函數(shù)注入,因?yàn)樗试S將應(yīng)用程序組件實(shí)現(xiàn)為不可變對(duì)象玩般,并確保所需的依賴項(xiàng)不是null列赎。此外型豁,構(gòu)造函數(shù)注入的組件總是以完全初始化的狀態(tài)返回給客戶端(調(diào)用)代碼稚机。作為補(bǔ)充說明,大量的構(gòu)造函數(shù)參數(shù)是一種糟糕的代碼味道,這意味著類可能有太多的職責(zé),應(yīng)該重構(gòu)它們狞玛,以便更好地處理關(guān)注點(diǎn)的適當(dāng)分離。Setter注入應(yīng)該主要用于可選依賴項(xiàng)涧窒,這些依賴項(xiàng)可以在類中分配合理的默認(rèn)值心肪。否則,必須在代碼使用依賴項(xiàng)的任何地方執(zhí)行非空檢查纠吴。setter注入的一個(gè)好處是硬鞍,setter方法使該類的對(duì)象可以在以后重新配置或重新注入。
依賴不可變:其實(shí)說的就是final關(guān)鍵字戴已,寫法就是(private?final?Service service;)
依賴不為空:當(dāng)實(shí)例化Controller的時(shí)候固该,由于自己實(shí)現(xiàn)了有參數(shù)的構(gòu)造函數(shù),所以不會(huì)調(diào)用默認(rèn)構(gòu)造函數(shù)糖儡,那么就需要Spring容器傳入所需要的參數(shù)伐坏。
完全初始化的狀態(tài):我的理解向構(gòu)造器傳參之前,要確保注入的內(nèi)容不為空握联,通過調(diào)用依賴組件的構(gòu)造方法完成實(shí)例化桦沉。(Java類加載實(shí)例化過程:父類-->自己的成員變量-->構(gòu)造方法)每瞒。所以返回來的都是初始化之后的狀態(tài)。
通過查詢各種資料和發(fā)現(xiàn)使用構(gòu)造函數(shù)注入的優(yōu)點(diǎn)和缺點(diǎn)如下:
優(yōu)點(diǎn):
????依賴不可變(加了final關(guān)鍵字)
????依賴不為空(省去了檢查)
????完全初始化的狀態(tài)
????避免了循環(huán)依賴
????提升了代碼的可復(fù)用性
缺點(diǎn):
????構(gòu)造函數(shù)會(huì)有很多參數(shù)纯露。
????有些類是需要默認(rèn)構(gòu)造函數(shù)的剿骨,一旦使用構(gòu)造函數(shù)注入,就無法使用默認(rèn)構(gòu)造函數(shù)埠褪。
????這個(gè)類里面的有些方法并不需要用到這些依賴浓利。
最后給大家提供IntelliJ IDEA @Autowired 快速切換成構(gòu)造注入的快捷鍵:
按Alt+Enter(回車鍵)
選擇自己需要的按回車鍵ok。