之前理解的是通過Spring等依賴注入框架自動幫我們創(chuàng)建對象,并通過解析注解或XML等方式獲取預(yù)先配置好的依賴關(guān)系來自動構(gòu)建好依賴才能稱為依賴注入。而手動創(chuàng)建對象并通過構(gòu)造方法傳入并不能稱為依賴注入。
今天看Effective Java才發(fā)現(xiàn)我之前的理解完全是錯誤的,正常通過構(gòu)造方法傳入?yún)?shù)也是依賴注入的一種形式,依賴注入這個概念是相對于單例和靜態(tài)工具類來說的。而Spring等框架只是用來管理復(fù)雜的依賴關(guān)系以消除依賴注入所帶來的復(fù)雜性。
以下是Effective Java第三版原文:
What is required is the ability to support multiple instances of the class (in our
example, SpellChecker ), each of which uses the resource desired by the client (in
our example, the dictionary). A simple pattern that satisfies this requirement is to
pass the resource into the constructor when creating a new instance. This is
one form of dependency injection: the dictionary is a dependency of the spell
checker and is injected into the spell checker when it is created.
The dependency injection pattern is so simple that many programmers use it
for years without knowing it has a name. While our spell checker example had
only a single resource (the dictionary), dependency injection works with an
arbitrary number of resources and arbitrary dependency graphs. It preserves
immutability (Item 17), so multiple clients can share dependent objects (assuming
the clients desire the same underlying resources). Dependency injection is equally
applicable to constructors, static factories (Item 1), and builders (Item 2).
...
Although dependency injection greatly improves flexibility and testability, it
can clutter up large projects, which typically contain thousands of dependencies.
This clutter can be all but eliminated by using a dependency injection framework,
such as Dagger [Dagger], Guice [Guice], or Spring [Spring]. The use of these
frameworks is beyond the scope of this book, but note that APIs designed for
manual dependency injection are trivially adapted for use by these frameworks.
然后去官方文檔重新查閱了Spring的IoC介紹,個人現(xiàn)在的理解是依賴注入和控制反轉(zhuǎn)是同一個概念的兩種不同的說法,基本思想就是把類的依賴從在類內(nèi)部構(gòu)建轉(zhuǎn)化到通過用戶程序在外部創(chuàng)建并注入到對象中以減少依賴。
關(guān)于依賴注入
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。