java - 理解java中的DI

标签 java spring dependency-injection coding-style

Possible Duplicate:
Understanding the need for a DI framework

我读过几篇关于 DI 的文章并与几位专业人士进行了交谈。我不明白的是如何 DI 解耦对象。下面的文章也描述了一个场景,但我不明白Spring如何帮助解耦PayrollApplication?解耦是通过多态而不是 DI 来完成的。 DI 定义还有其他一些目的......

http://www.developer.com/java/dependency-injection-in-existing-java-code.html

提示和引用就可以了。谢谢

最佳答案

解耦不是一个全有或全无的概念。在本文中,仅使用多态性(“设计 2”)在一定程度上解耦了对象,但在编译 PayrollApplication 时,PayrollApplication 类仍然必须了解 Employee 实现。

Employee 实现是 PayrollApplication 的依赖项,通过依赖注入(inject),您可以实现更高级别的解耦:您可以编译 PayrollApplication,使其仅引用 Employee 接口(interface),并提供 Employee 实现(可能由另一个团队编写)组织)稍后再说。

另请查看 Wikipedia关于依赖注入(inject):

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. The pattern is particularly useful for providing stub test implementations of complex components when testing, but is often used for locating plugin components, or locating and initializing software services.

关于java - 理解java中的DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14485594/

相关文章:

java - 为什么 Spring 单例范围的 bean 比经典的单例模式更好?

c# - 从 MVC 中的 Controller 构造函数中删除依赖项

java - 将线程分配给变量来控制它

java - 定义一个数据输入检查方法并调用它没有帮助,android

java - 如何在Spring拦截器中读取httpservletresponse?

java - 如何在Spring Security中定义模式?

java - 如何使用带有辅助注入(inject)的模拟对象而不是真正的实现类

java - 如何在 TERRIER 信息检索系统中使用 YASS 或 GRAS 等统计词干分析器代替 Porter 词干分析器

java - Vaadin:日历插件存在问题 - 无法编译小部件集

java - 如何将 session 属性传递给 ThymeLeaf 表单字段以保存到数据库中