创建新对象和依赖注入的区别 [英] Difference between creating new object and dependency injection

查看:59
本文介绍了创建新对象和依赖注入的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建新对象和依赖注入有什么区别?请详细说明.

What is the difference between creating a new object and dependency injection? Please explain in detail.

推荐答案

嗯,创建新对象尽可能明确 - 您可以创建所需类的新实例.

Well, creating a new object is as explicit as it can get - you create a new instance of the desired class.

依赖注入是一种机制,可在您需要的地方提供参考.想象一个代表数据库连接池的类——您通常只有该类的一个实例.现在您需要将该引用分发给所有使用它的类.这就是依赖注入派上用场的地方 - 通过使用诸如 Spring 之类的 DI 框架,您可以定义将池的一个实例注入到需要它的类中.

Dependency injections is a mechanism that provides you with references where you need them. Imagine a class that represents a connection pool to your database - you usually only have one instance of that class. Now you need to distribute that reference to all the classes that use it. Here is where Dependency Injection comes in handy - by using a DI framework such as Spring you can define that the one instance of your pool will be injected into the classes that need it.

你的问题本身并不容易回答,因为对象的创建和依赖注入不能那么容易地进行比较......

Your question itself is not easy to answer since the creation of an object and dependency injection can't be compared that easily...

这篇关于创建新对象和依赖注入的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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