本文介绍了了解对 DI 框架的需求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个幼稚的问题.我目前正在学习 Spring 框架和依赖注入.虽然 DI 的基本原理很容易掌握,但为什么需要一个精心设计的框架来实现它并不是很明显.

This might be a naive question. I'm currently learning the Spring framework and dependency injection. While the basic principle of DI is rather easy to grasp, it's not immediately obvious why you need an elaborate framework to implement it.

考虑以下事项:

public abstract class Saw
{
    public abstract void cut(String wood);
}

public class HandSaw extends Saw
{
    public void cut(String wood)
    {
        // chop it up
    }
}

public class ChainSaw extends Saw
{
    public void cut(String wood)
    {
        // chop it a lot faster
    }
}

public class SawMill
{
    private Saw saw;

    public void setSaw(Saw saw)
    {
        this.saw = saw;
    }

    public void run(String wood)
    {
        saw.cut("some wood");
    }
}

那么你可以简单地做:

Saw saw = new HandSaw();
SawMill sawMill = new SawMill();
sawMill.setSaw(saw);
sawMill.run();

相当于:

<bean id="saw" class="HandSaw"/>

<bean id="sawMill" class="SawMill">
   <property name="saw" ref="saw"/>
</bean>

加:

ApplicationContext context = new ClassPathXmlApplicationContext("sawmill.xml");
SawMill springSawMill = (SawMill)context.getBean("sawMill");
springSawMill.run();

诚然,这是一个人为的例子,对于更复杂的对象关系,存储一个 XML 文件可能比以编程方式编写它更有效,但肯定不止于此?

Granted, this is a contrieved example, and with more complex object relationships it might be more efficient to stash up an XML file than writing it programmatically, but surely there must be more to it than that?

(我知道 Spring 框架不止于此,但我在考虑是否需要一个 DI 容器.)

(I know the Spring framework is more than that, but I'm thinking of the need for a DI container.)

在第一个示例中,在中途更改依赖项也很简单:

In the first example it would also be trivial to change dependencies midstream:

// gotta chop it faster
saw = new ChainSaw();
sawMill.setSaw(saw);
sawMill.run();

推荐答案

依赖注入是 隐式参数传递,和目的基本一样,解决所谓的配置问题:

Dependency injection is a degenerate form of implicit parameter passing, and the purpose is essentially the same, to solve what's called The Configurations Problem:

配置问题是传播运行时首选项在整个程序中,允许多个并发配置集在静态下安全共存保证分离.

依赖注入框架弥补了隐式参数咖喱函数,以及monads 在语言中.

Dependency Injection frameworks compensate for the lack of implicit parameters, Curried functions, and convenient facilities for monads in the language.

这篇关于了解对 DI 框架的需求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 02:38