之前理解的是通过Spring等依赖注入框架自动帮我们创建对象,并通过解析注解或XML等方式获取预先配置好的依赖关系来自动构建好依赖才能称为依赖注入。而手动创建对象并通过构造方法传入并不能称为依赖注入。
今天看Effective Java才发现我之前的理解完全是错误的,正常通过构造方法传入参数也是依赖注入的一种形式,依赖注入这个概念是相对于单例和静态工具类来说的。而Spring等框架只是用来管理复杂的依赖关系以消除依赖注入所带来的复杂性。
以下是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介绍,个人现在的理解是依赖注入和控制反转是同一个概念的两种不同的说法,基本思想就是把类的依赖从在类内部构建转化到通过用户程序在外部创建并注入到对象中以减少依赖。
关于依赖注入
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...