Possible Duplicates:
What is dependency injection?
What exactly is Spring for?
我想知道 什么是 Spring 框架?为什么以及何时应该在 Java 企业开发中使用它? 答案是“依赖注入(inject)框架”。 好吧,我们在使用依赖注入(inject)框架时有什么优势呢? 用 setter 值和/或构造函数参数描述类的想法对我来说似乎很奇怪。 为什么要这样做?因为我们可以在不重新编译项目的情况下更改属性?这就是我们的全部收获吗?
那么,我们应该在 beans.xml
中描述哪些对象?所有对象还是只有少数?
欢迎最简单的答案
最佳答案
我们使用依赖注入(inject) (DI) 来实现松散耦合。任何特定的 DI 容器的选择并不那么重要。
每次使用 new
关键字创建类的实例时,您的代码都会与该类紧密耦合,并且您将无法用不同的实现替换该特定实现(至少在不重新编译代码的情况下是这样)。
这在 C# 中看起来像这样(但在 Java 中是等价的):
public class MyClass
{
public string GetMessage(int key)
{
return new MessageService().GetMessage(key)
}
}
这意味着如果您以后想使用不同的 MessageService,则不能。
另一方面,如果您将接口(interface)注入(inject)到类中并遵守 Liskov Substition Principle ,您将能够独立地改变消费者和服务。
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)
}
}
虽然这看起来更复杂,但我们现在已经设法遵循 Single Responsibility Principle通过确保每个合作者只做一件事,并且我们可以相互独立地改变两者。
此外,我们现在可以在不更改类本身的情况下更改 MyClass 的行为,从而遵守 Open/Closed Principle .
关于java - 什么是依赖注入(inject)和 Spring 框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1980182/