gpt4 book ai didi

dependency-injection - 在依赖注入(inject)中什么是依赖?

转载 作者:行者123 更新时间:2023-12-01 09:33:56 24 4
gpt4 key购买 nike

我已经阅读了很多关于此的内容,但我仍然不清楚这些事情。我们说 DI 就是在运行时将依赖注入(inject)到依赖组件中

第一季度

What is a dependency ? If these are the objects created at runtime?

如果是,这是否意味着我们通过创建对象将值注入(inject)变量(由框架创建,即通过 xml 文件使用 setter/constructor 注入(inject)实例化 bean)

第二季度

We do the DI to do work without object intervention?

最佳答案

第一季度

来自 Wikipedia ,DI模式中的所有元素都是对象。 dependent 对象使用接口(interface)指定它需要什么。 injector 对象决定了哪些具体类(实例化对象)可以满足需求并将它们提供给依赖对象。

所以,这变成了第二部分的

第二季度

再次来自 Wikipedia :

The primary purpose of the dependency injection pattern is to allow selection among multiple implementations of a given dependency interface at runtime, or via configuration files, instead of at compile time.

作为一个例子,考虑一个安全服务,它可以工作在 Encoder 的不同实现中。不同的编码算法可能包括 SHA、MD5 等。安全服务只指定它需要一个“编码算法”的实例。然后,运行时 DI 环境将寻找提供 Encoder 接口(interface)的对象,然后注入(inject)到安全服务中。根据 DI,安全服务也在利用 Inversion of Control (IoC) ;即,它自己不决定使用什么实现,而是由 DI 运行时做出决定。

关于dependency-injection - 在依赖注入(inject)中什么是依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11814700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com