美文网首页
关于依赖注入

关于依赖注入

作者: 书山压力特别大 | 来源:发表于2019-04-05 21:59 被阅读0次

之前理解的是通过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介绍,个人现在的理解是依赖注入和控制反转是同一个概念的两种不同的说法,基本思想就是把类的依赖从在类内部构建转化到通过用户程序在外部创建并注入到对象中以减少依赖。

相关文章

  • Dagger2基本使用

    Dagger2是一个依赖注入框架,目前由google维护。关于依赖注入是什么可以看依赖注入简介 引入Dagger ...

  • 关于依赖注入

    摘自 Spring In Action 一书,第一章第一节。 DI (dependency injection)并...

  • 关于依赖注入

    之前理解的是通过Spring等依赖注入框架自动帮我们创建对象,并通过解析注解或XML等方式获取预先配置好的依赖关系...

  • 7、angular学习第六天 (依赖注入的理解)

    一、关于依赖注入 关于angular的依赖注入学习。。有种很奇怪的感觉。我在学习过程中竟然对java的Spring...

  • day02 IoC/DI学习

    DI(依赖注入)是Martin Fowler 在2004年提出的关于IoC(控制反转)的解释,依赖注入和控制反转其...

  • 关于laravel依赖注入

    关于laravel依赖注入和IoC容器的个人理解: 关于它的实现方式 我们要的最后结果就是:注入,只要注入就OK ...

  • 浅谈spring boot控制反转的相关问题

    控制反转,和依赖注入是同一个意思,我觉得应该重点去了解什么是依赖,而后控制反转、依赖注入就有体会了;关于依赖,可以...

  • 开源项目的依赖注入

    开源项目的依赖注入 依赖注入概念 依赖注入(DI:Dependency Injection): 依赖注入方式: B...

  • 关于依赖注入(typescript)

    一、概念:依赖注入(DI)、控制反转(IOC)、IOC容器 依赖注入(DI)和控制反转(IOC)基本是一个意思,因...

  • day03 IoC学习

    依赖注入是Martin Fowler 在2004年提出的关于IoC(控制反转)的解释,依赖注入和控制反转其实就是一...

网友评论

      本文标题:关于依赖注入

      本文链接:https://www.haomeiwen.com/subject/xklqiqtx.html