Java 什么是依赖注入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3334578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is Dependency Injection?
提问by
Possible Duplicate:
What is dependency injection?
可能的重复:
什么是依赖注入?
Spring is the framework from where the concept Dependency Injection came to picture.
Spring 是依赖注入概念出现的框架。
What is purpose of DI ? How does it benefit ? How is it implemented ?
DI 的目的是什么?它如何受益?它是如何实施的?
采纳答案by Zaki
Start here.
从这里开始。
Also see A-beginners-guide-to-Dependency-Injection. (Obsolete)
另请参阅A-beginners-guide-to-Dependency-Injection。(过时的)
Elsewhere on SO:
SO的其他地方:
回答by pdbartlett
Try taking a look at: http://martinfowler.com/articles/injection.html
回答by PaulJWilliams
回答by Justin Niessner
What is the purpose of DI?
DI的目的是什么?
The purpose of Dependency Injection is to reduce coupling in your application to make it more flexible and easier to test.
依赖注入的目的是减少应用程序中的耦合,使其更加灵活和易于测试。
How does it benefit?
它如何受益?
Objects don't have hard coded dependencies. If you need to change the implementation of a dependency, all you have to do is Inject a different type of Object.
对象没有硬编码的依赖关系。如果您需要更改依赖项的实现,您所要做的就是注入不同类型的对象。
How does it implemented?
它是如何实施的?
There are various methods of Dependency Injection. Check out the Wikipedia articleto see examples of each. Once you understand those, you can start investigating the various Dependency Injection frameworks.
依赖注入有多种方法。查看Wikipedia 文章以查看每个示例。一旦你理解了这些,你就可以开始研究各种依赖注入框架。
回答by TrustyCoder
DI allows us to swap out components, improve testability and ensure that components are loosely coupled. DI allows to resolve dependencies at run time using DI containers such as Windsor Castle, Unity, Spring.net, MEF which allows applications to be extensible.
DI 允许我们更换组件,提高可测试性并确保组件松散耦合。DI 允许在运行时使用 DI 容器(例如 Windsor Castle、Unity、Spring.net、MEF)解决依赖关系,这些容器允许应用程序可扩展。
回答by nkr1pt
Very short,
很短,
What is the purpose of DI?With dependency injection, objects don't define their dependencies themselves, the dependencies are injected to them as needed.
DI的目的是什么?使用依赖注入,对象本身并不定义它们的依赖,依赖会根据需要注入它们。
How does it benefit ?The objects don't need to know where and how to get their dependencies, which results in loose coupling between objects, which makes them a lot easier to test.
它如何受益?对象不需要知道在哪里以及如何获取它们的依赖关系,这导致对象之间的松散耦合,这使得它们更容易测试。
How is it implemented ?Usually a container manages the lifecycle of objects and their dependencies based on a configuration file or annotations.
它是如何实施的?通常,容器根据配置文件或注解管理对象及其依赖项的生命周期。