美文网首页
关于依赖注入

关于依赖注入

作者: 书山压力特别大 | 来源:发表于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介绍,个人现在的理解是依赖注入和控制反转是同一个概念的两种不同的说法,基本思想就是把类的依赖从在类内部构建转化到通过用户程序在外部创建并注入到对象中以减少依赖。

    相关文章

      网友评论

          本文标题:关于依赖注入

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