关于spring:我解释DI和IoC的方式有什么问题?

What is wrong in my way of explainning DI and IoC?

昨天在一次采访中,我被问到春季的DI和IOC是什么。我的回答是:

when a class(A) extends abstract class(B) or implements interface(B)
or create a object of class(B) of any class in it, then A is said said to be
dependent on B. Injecting this dependency, i.e. injecting the object in
costructor or in setter method is called DI and in this process
control over creating object goes to the"outside world" like XML
configuration, this inversion of control is IoC. DI is not necessary IOC. We can still have DI when there is no IOC.

面试官不同意我的看法——我哪里错了?

还有一件事——

As we used Super class reference variable or coding through interface in constructor or setter method parameter.Is this any way
related with DI/IOC or this is only to achieve loose coupling?


第一条语句***"当类(a)扩展抽象类(b)或实现接口(b)"***

这是继承,不能通过Spring作为依赖注入

第二个声明"在其中创建任何类的类(B)的对象,则称A依赖于B"

听起来不错

注入这种依赖关系,即在costructor或setter方法中注入对象,称为di。

没有明确的声明来解释依赖注入。这里需要解释注射的含义。也就是说依赖项的管理由Spring容器处理,它控制它们的生命周期,从而委托/注入请求它们的类(通过Spring配置文件)。

他对创建对象的过程控制转到"外部世界",如XML配置

这里的控件既不指向外部世界,也不指向XML配置文件,而是指向Spring容器。Spring容器使用这个配置文件来完成它的工作。

"这种控制权的倒置是国际奥委会。国际奥委会不需要DI。在没有国际奥委会的情况下,我们仍然可以使用DI。"

虽然没有问题,但似乎不完整。这里需要解释国际奥委会。试图通过图像来解释

NON IOC VS IOC


IOC(控制反转)是一个抽象概念。这意味着对象不会直接创建依赖对象,而是从对象范围之外获取。

实现控制反转有几种基本技术。

  • 使用工厂模式
  • 使用服务定位器模式
  • 例如,使用依赖注入(DI)
    • 建设者注入
    • 参数注入
    • 设值注入
    • 界面注入
  • 使用上下文化查找
  • 使用模板方法设计图案
  • 使用策略设计模式

来源