什么是依赖注入Spring框架呢? [英] What are Dependency Injection & Spring Framework about?

查看:117
本文介绍了什么是依赖注入Spring框架呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复:

什么是依赖注入?

究竟是什么Spring for?

我想知道
什么是Spring Framework?为什么和何时应该在Java Enterprise开发中使用它?

答案将是依赖注入框架。
好​​的,使用依赖注入框架有什么优势?
使用setter值和/或构造函数参数描述类的想法对我来说似乎很奇怪。
为什么呢?因为我们可以改变属性而不重新编译项目?这是我们所获得的一切吗?

I want to know What is Spring Framework? Why and when should one use it in Java Enterprise development? The answer would be "A dependency injection framework". All right, what advantages do we have when using dependency injection frameworks? The idea of describing classes with setter values and/or constructor parameters seems strange to me. Why do that? Because we can change the properties without recompiling the project? Is that all what we gain?

然后,我们应该在beans.xml中描述什么对象?所有的对象或只有几个?

Then, what objects should we describe in beans.xml ? All objects or only a few ?

最简单的答案是欢迎的

推荐答案

p>我们使用依赖注入(DI)实现松耦合。任何特别的DI容器的选择并不重要。

We use Dependency Injection (DI) to implement loose coupling. The choice of any particulary DI Container is not that important.

每次使用新建关键字,你将代码紧密地耦合到该类,并且你将无法用其他代码替代该特定的实现(至少不能重新编译代码)。

Every time you create an instance of a class by using the new keyword, you tightly couple your code to that class, and you will not be able to substitute that particularl implementation with a different one (at least not without recompiling the code).

这将在C#中看起来像这样(但在Java中将是等同的):

This would look something like this in C# (but would be equivalent in Java):

public class MyClass
{
    public string GetMessage(int key)
    {
        return new MessageService().GetMessage(key)
    }
}

这意味着如果你以后想使用不同的MessageService,你不能。

This means that if you would later like to use a different MessageService, you can't.

另一方面,如果您将一个界面注入课堂,并遵守 Liskov Substance原则,您将能够改变使用情况mer和服务独立。

On the other hand, if you inject an interface into the class and adhere to the Liskov Substition Principle, you will be able to vary the consumer and the service independently.

public class MyClass
{
    private readonly IMessageService messageService;

    public MyClass(IMessageService messageService)
    {
        if(messageService == null)
        {
            throw new ArgumentNullException("messageService");
        }

        this.messageService = messageService;
    }

    public string GetMessage(int key)
    {
        return this.messageService.GetMessage(key)
    }
}

虽然这看起来更复杂,我们现在已经设法遵循单一责任原则

Although this looks more complicated, we have now managed to follow the Single Responsibility Principle by ensuring that each collaborator does only one thing, and that we can vary both independently of each other.

此外,我们现在可以更改MyClass的行为而不改变类本身,因此遵守开/关原则

Furthermore, we can now change MyClass' behavior without changing the class itself, thus adhering to the Open/Closed Principle.

这篇关于什么是依赖注入Spring框架呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆