当前位置: 首页 > 编程日记 > 正文

框架依赖注入和普通依赖注入_依赖注入快速入门:它是什么,以及何时使用它...

框架依赖注入和普通依赖注入

by Bhavya Karia

通过Bhavya Karia

介绍 (Introduction)

In software engineering, dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service).

在软件工程中 , 依赖注入是一种技术,通过该技术,一个对象(或静态方法)可以提供另一对象的依赖关系。 依赖项是可以使用的对象( 服务 )。

That’s the Wikipedia definition but still, but it’s not particularly easy to understand. So let’s understand it better.

那是Wikipedia的定义,但仍然不是很容易理解。 因此,让我们更好地了解它。

Before understanding what it means in programming, let’s first see what it means in general as it will help us understand the concept better.

在理解编程的含义之前,让我们首先了解一下它的总体含义,因为它可以帮助我们更好地理解该概念。

Dependency or dependent means relying on something for support. Like if I say we are relying too much on mobile phones than it means we are dependent on them.

依赖或依赖是指依靠某种东西来获得支持。 就像我说过,我们对手机的依赖程度过高,这意味着我们对手机的依赖程度高。

So before getting to dependency injections, first let’s understand what a dependency in programming means.

因此,在进行依赖注入之前,首先让我们了解编程中的依赖意味着什么。

When class A uses some functionality of class B, then its said that class A has a dependency of class B.

当类A使用类B的某些功能时,则表示类A具有类B的依赖项。

In Java, before we can use methods of other classes, we first need to create the object of that class (i.e. class A needs to create an instance of class B).

在Java中,在使用其他类的方法之前,我们首先需要创建该类的对象(即,类A需要创建类B的实例)。

So, transferring the task of creating the object to someone else and directly using the dependency is called dependency injection.

因此,将创建对象的任务转移给其他人并直接使用依赖项的过程称为依赖项注入。

为什么要使用依赖注入? (Why should I use dependency injection?)

Let’s say we have a car class which contains various objects such as wheels, engine, etc.

假设我们有一个car类,其中包含各种对象,例如车轮,引擎等。

Here the car class is responsible for creating all the dependency objects. Now, what if we decide to ditch MRFWheels in the future and want to use Yokohama Wheels?

汽车类在这里负责创建所有依赖项对象。 现在,如果我们决定将来放弃MRFWheels ,并希望使用横滨车轮,该怎么办?

We will need to recreate the car object with a new Yokohama dependency. But when using dependency injection (DI), we can change the Wheels at runtime (because dependencies can be injected at runtime rather than at compile time).

我们将需要使用新的横滨依赖关系来重新创建汽车对象。 但是,当使用依赖项注入(DI)时,我们可以在运行时更改Wheels(因为可以在运行时而不是在编译时注入依赖项)。

You can think of DI as the middleman in our code who does all the work of creating the preferred wheels object and providing it to the Car class.

您可以将DI视为我们代码中的中间人,他负责创建首选的wheel对象并将其提供给Car类的所有工作。

It makes our Car class independent from creating the objects of Wheels, Battery, etc.

它使我们的Car类独立于创建Wheels,Battery等对象。

基本上有三种类型的依赖项注入: (There are basically three types of dependency injection:)

  1. constructor injection: the dependencies are provided through a class constructor.

    构造函数注入:依赖关系是通过类构造函数提供的。

  2. setter injection: the client exposes a setter method that the injector uses to inject the dependency.

    setter注入:客户端公开了setter方法,注入程序用于注入依赖项。

  3. interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

    接口注入:依赖项提供了一个注入器方法,该方法会将依赖项注入到传递给它的任何客户端中。 客户端必须实现一个接口,该接口公开一个接受依赖项的setter方法 。

So now its the dependency injection’s responsibility to:

因此,现在依赖注入的职责是:

  1. Create the objects

    创建对象
  2. Know which classes require those objects

    了解哪些类需要这些对象
  3. And provide them all those objects

    并提供所有这些对象

If there is any change in objects, then DI looks into it and it should not concern the class using those objects. This way if the objects change in the future, then its DI’s responsibility to provide the appropriate objects to the class.

如果对象有任何更改,则DI会对其进行调查,并且它不应该涉及使用这些对象的类。 这样,如果对象在将来发生变化,则其DI负责为类提供适当的对象。

控制反转-DI背后的概念 (Inversion of control —the concept behind DI)

This states that a class should not configure its dependencies statically but should be configured by some other class from outside.

这说明一个类不应静态配置其依赖项,而应由其他一些类从外部进行配置。

It is the fifth principle of S.O.L.I.D — the five basic principles of object-oriented programming and design by Uncle Bob — which states that a class should depend on abstraction and not upon concretions (in simple terms, hard-coded).

这是SOLID的第五项原则- Bob叔叔提出的面向对象编程和设计的五项基本原则-指出类应该依赖抽象而不是具体(简单地说,就是硬编码)。

According to the principles, a class should concentrate on fulfilling its responsibilities and not on creating objects that it requires to fulfill those responsibilities. And that’s where dependency injection comes into play: it provides the class with the required objects.

根据这些原则,一个班级应该专注于履行职责,而不是创建履行职责所需要的对象。 这就是依赖注入起作用的地方:它为类提供了所需的对象。

Note: If you want to learn about SOLID principles by Uncle Bob then you can head to this link.

注意:如果您想了解Bob叔叔的SOLID原理,则可以转到此链接 。

使用DI的好处 (Benefits of using DI)

  1. Helps in Unit testing.

    帮助进行单元测试。
  2. Boiler plate code is reduced, as initializing of dependencies is done by the injector component.

    由于依赖关系的初始化是由喷油器组件完成的,因此减少了锅炉板代码。
  3. Extending the application becomes easier.

    扩展应用程序变得更加容易。
  4. Helps to enable loose coupling, which is important in application programming.

    帮助实现松耦合,这在应用程序编程中很重要。

DI的缺点 (Disadvantages of DI)

  1. It’s a bit complex to learn, and if overused can lead to management issues and other problems.

    学习起来有点复杂,如果使用过度会导致管理问题和其他问题。
  2. Many compile time errors are pushed to run-time.

    许多编译时错误被推送到运行时。
  3. Dependency injection frameworks are implemented with reflection or dynamic programming. This can hinder use of IDE automation, such as “find references”, “show call hierarchy” and safe refactoring.

    依赖注入框架是通过反射或动态编程实现的。 这可能会妨碍IDE自动化的使用,例如“查找引用”,“显示调用层次结构”和安全重构。

You can implement dependency injection on your own (Pure Vanilla) or use third-party libraries or frameworks.

您可以自己(纯Vanilla)实现依赖项注入,也可以使用第三方库或框架。

实现DI的库和框架 (Libraries and Frameworks that implement DI)

  • Spring (Java)

    Spring (Java)

  • Google Guice (Java)

    Google Guice (Java)

  • Dagger (Java and Android)

    匕首 (Java和Android)

  • Castle Windsor (.NET)

    温莎城堡 (.NET)

  • Unity(.NET)

    Unity (.NET)

To learn more about dependency injection, you can check out the below resources:

要了解有关依赖项注入的更多信息,您可以查看以下资源:

Java Dependency Injection — DI Design Pattern Example Tutorial — JournalDev

Java依赖注入— DI设计模式示例教程— JournalDev

Using dependency injection in Java — Introduction — Tutorial — Vogella

在Java中使用依赖注入—简介—教程— Vogella

Inversion of Control Containers and the Dependency Injection pattern — Martin Fowler

控制容器的反转和依赖注入模式— Martin Fowler

Hope it helps!

希望能帮助到你!

If you liked the article and want to read more amazing articles, then do follow me here (Bhavya Karia) and show your support as it motivates me to write more.

如果您喜欢这篇文章并想精彩的文章,请在这里关注我( Bhavya Karia ),并表达您的支持,因为它激发了我写更多文章的动力。

If you have any questions or feedback for me than let’s connect on LinkedIn, Twitter , Facebook.

如果您对我有任何疑问或反馈,请让我们在LinkedIn, Twitter, Facebook上进行连接 。

编辑1: (Edit 1:)

Thanks to Sergey Ufocoder now this article has been converted into the Russian language. My Russian friends and who all can read the Russian language do give it a read.

感谢Sergey Ufocoder,现在这篇文章已被转换成俄语。 我的俄罗斯朋友以及所有人都可以读俄文的确可以读一读。

Link to the article

链接到文章

Also, if you want to apply DI in JavaScript and are looking for a library then Jo Surikat suggests that you give a try to his library.

另外,如果您想在JavaScript中应用DI并正在寻找一个库,那么Jo Surikat建议您尝试一下他的库。

Di-Ninja

忍者

One more awesome DI library in JavaScript was suggested by Nicolas Froidure.

Nicolas Froidure提出了JavaScript中另一个很棒的DI库。

knifecycle

刀轮

编辑2: (Edit 2:)

If you are a PHP developer then don’t worry, got you all covered as well. Gordon Forsythe recommended this amazing library which you all might want to try out.

如果您是PHP开发人员,那么请不要担心,也涵盖了所有方面。 Gordon Forsythe推荐了这个令人惊叹的库,您可能想尝试一下。

auryn

奥林

Thanks for all the kind words that I have been receiving. Do share the article so that more and more people can be benefited.

感谢您收到的所有客气话。 一定要分享文章,以便使越来越多的人受益。

If you learnt even a thing or two, please share this story!

如果您只学会了一两件事,请分享这个故事!

翻译自: https://www.freecodecamp.org/news/a-quick-intro-to-dependency-injection-what-it-is-and-when-to-use-it-7578c84fa88f/

框架依赖注入和普通依赖注入

相关文章:

微信小程序自定义弹出框组件,模拟wx.showModal

微信小程序开发交流qq群 173683895 效果图&#xff1a; 代码 wxml <view wx:if{{showModal}}><view classmask_layer bindtapmodal_click_Hidden /><view classmodal_box><view class"title">取消订单</view><view classconte…

IOS tableView删除数据

NSMutableArray *_allshops; NSMutableArray *_deleteshops; -(IBAction)remove{ 1. //记录删除的行号 //创建动态数组存放行号的集合 NSMutableArray *deletepath [NSMutableArray array]; //遍历存放删除数据的数组&#xff0c;把行号放到deletepath中 for (Shop * s in _de…

vue.js 源代码学习笔记 ----- 工具方法 lang

/* flow */ // Object.freeze 使得这个对象不能增加属性, 修改属性, 这样就保证了这个对象在任何时候都是空的 export const emptyObject Object.freeze({}) /*** Check if a string starts with $ or _ ascii unicode 的区别 charcodeAt是一个字符的 unicode编码, 但是…

Tim Berners-Lee重新分散的新Web SOLID简介

by Arnav Bansal通过Arnav Bansal Tim Berners-Lee重新分散的新Web SOLID简介 (An introduction to SOLID, Tim Berners-Lee’s new, re-decentralized Web) Recently, Prof. Tim Berners-Lee lifted the veil off a project called Solid. I decided to check it out. In thi…

AngularJS2.0 教程系列(一)

Why Angular2 Angular1.x显然非常成功&#xff0c;那么&#xff0c;为什么要剧烈地转向Angular2&#xff1f; 性能的限制 AngularJS当初是提供给设计人员用来快速构建HTML表单的一个内部工具。随着时间的推移&#xff0c;各种特性 被加入进去以适应不同场景下的应用开发。然而由…

Vue组件绑定自定义事件

Vue组件使用v-on绑定自定义事件&#xff1a;   可以分为3步理解&#xff1a;     1.在组件模板中按照正常事件机制绑定事件&#xff1a;       template: <button v-on:click"increment">{{ counter }}</button>,       如上&#xff…

phpstudy本地调试运行TP5的后台源码

本地访问后台步骤&#xff1a; 1.打开 phpstudy 2.点击其它选项菜单 3.点击软件设置 4.点击端口常规设置 5.修改网站根目录为&#xff1a; C:\phpStudy\PHPTutorial\WWW\wxpet_2019\public phpstudy 切换php版本&#xff1a;5.6.27 public目录下的 .htacc…

如何使用TensorFlow Eager执行训练自己的FaceID ConvNet

by Thalles Silva由Thalles Silva Faces are everywhere — from photos and videos on social media websites, to consumer security applications like the iPhone Xs FaceID.人脸无处不在-从社交媒体网站上的照片和视频到iPhone Xs FaceID等消费者安全应用程序。 In this…

jquery判断一个元素是否为某元素的子元素

$(node).click(function(){if($(this).parents(.aa).length > 0){//是aa类下的子节点}else{//不是aa类下的子节点} });在判断点击body空白处隐藏弹出框时用到转载于:https://www.cnblogs.com/qdog/p/7067909.html

Sublime Text 3 (含:配置 C# 编译环境)

Sublime Text 3http://www.sublimetext.com/3http://www.sublimetext.com/3dev1. 关闭自动更新 菜单&#xff1a;Preferences->Settings User&#xff0c;打开User配置文档&#xff0c;在大括号内加入&#xff08;或更改&#xff09;&#xff1a; "update_check&q…

小程序仿安卓动画滑动效果滑动动画效果实现

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 效果图&#xff1a; 源码 var start_clientY; //记录当前滑动开始的值 var end_clientY; //记录当前滑动结束的值 var animation wx.createAnimation({duration: 400 }); //初始化动画var history_dis…

react中使用scss_我如何将CSS模块和SCSS集成到我的React应用程序中

react中使用scssby Max Goh由Max Goh 我如何将CSS模块和SCSS集成到我的React应用程序中 (How I integrated CSS Modules with SCSS into my React application) I recently started on an Isomorphic React project. I wanted to use this opportunity to utilize tools that …

-bash:syntax error near unexpected token '('

在Xshell5中编写int main(int argc,char** argv)时&#xff0c; 出现-bash:syntax error near unexpected token ( &#xff1b; 可是我是按照Linux语句编写的&#xff0c;其他代码没有出错&#xff1b; 检查发现&#xff0c; Xshell5对应的Linux版本是Linux5&#xff0c;在Li…

iOS手机 相册 相机(Picker Write)

把图片写到相册UIImageWriteToSavedPhotosAlbum(<#UIImage *image#>, nil, nil, nil); ————————————————————————————从相册&#xff0c;相机获取图像设置代理《UINavigationControllerDelegate, UIImagePickerControllerDelegate》 #pragm…

php删除指定对象的属性及属性值

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 unset($address[/Api/User/addAddress]); 删除了 address 对象的 /Api/User/addAddress 属性

前端分离的前端开发工具_使我成为前端开发人员工作的工具和资源

前端分离的前端开发工具Learning front-end development can be a bit overwhelming at times. There are so many resources and tools, and so little time. What should you pick? And what should you focus on?有时&#xff0c;学习前端开发可能会有些困难。 资源和工具…

C# 开启及停止进程

1.本篇内容转发自http://www.cnblogs.com/gaoyuchuanIT/articles/2946314.html 2. 首先在程序中引用: System.Diagnostics; 3. 开启进程: /// <summary> /// 开启进程 /// </summary> /// <param name"aProPath&quo…

COJN 0575 800601滑雪

800601滑雪难度级别&#xff1a;B&#xff1b; 运行时间限制&#xff1a;1000ms&#xff1b; 运行空间限制&#xff1a;51200KB&#xff1b; 代码长度限制&#xff1a;2000000B 试题描述Michael喜欢滑雪百这并不奇怪&#xff0c; 因为滑雪的确很刺激。可是为了获得速度&#xf…

JS删除数组指定下标并添加到数组开头

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 代码 let id e.currentTarget.dataset.idlet arrays ;let items this.data.itemsfor (let i 0; i < this.data.items.length; i) {if (id this.data.items[i].id) {arrays items.splice(i, 1)i…

scala akka_如何对Scala和Akka HTTP应用程序进行Docker化-简单的方法

scala akkaby Miguel Lopez由Miguel Lopez 如何对Scala和Akka HTTP应用程序进行Docker化-简单的方法 (How to Dockerise a Scala and Akka HTTP Application — the easy way) Using Docker is a given nowadays. In this tutorial we will how to learn to dockerise our Sca…

Freemarker详细解释

A概念 最经常使用的概念1、 scalars&#xff1a;存储单值字符串&#xff1a;简单文本由单或双引號括起来。数字&#xff1a;直接使用数值。日期&#xff1a;通常从数据模型获得布尔值&#xff1a;true或false&#xff0c;通常在<#if …>标记中使用2、 hashes&#xff1a;…

洛谷P1057 传球游戏(记忆化搜索)

点我进入题目题目大意&#xff1a;n个小孩围一圈传球&#xff0c;每个人可以给左边的人或右边的人传球&#xff0c;1号小孩开始&#xff0c;一共传m次&#xff0c;请问有多少种可能的路径使球回到1号小孩。 输入输出&#xff1a;输入n&#xff0c;m&#xff0c;输出路径的数量。…

微信小程序 自定义导航栏,只保留右上角胶囊按钮

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 navigationStyle 导航栏样式&#xff0c;仅支持以下值&#xff1a;default 默认样式custom 自定义导航栏&#xff0c;只保留右上角胶囊按钮 在 app.json 的 window 加上 "navigationStyle":…

azure多功能成像好用吗_如何使用Azure功能处理高吞吐量消息

azure多功能成像好用吗Authored with Steef-Jan Wiggers, Azure MVP.由Azure MVP Steef-Jan Wiggers撰写。 With Microsoft Azure, customers will push all types of workloads to its services. Workloads are ranging from datasets for Machine Learning purposes to a la…

document.all使用

document.all 一个. document.all它是在页面中的所有元素的集合。例如&#xff1a; document.all(0)一个元素 二. document.all能够推断浏览器是否是IE if(document.all) { alert("is IE!"); } 三. 也能够通过给某个元素设置id属性&#xff08;id…

微信小程序动画无限循环 掉花

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 动画效果 源码 <!-- 动画 --><block wx:if"{{donghua}}"><view classdonghua><image bindtaphua styleleft:{{left1}}px animation"{{animationData1}}" clas…

程序员远程办公_如何从办公室变成远程程序员

程序员远程办公by James Quinlan詹姆斯昆兰(James Quinlan) My name is James, and I’m a Software Engineer at a company called Yesware, based in Boston. Yesware is the fourth job I’ve had in which I’m paid to write code, but it’s the third time now that I’…

从头学起androidlt;AutoCompleteTextView文章提示文本框.十九.gt;

文章提示可以很好的帮助用户输入信息&#xff0c;以方便。在Android它也设置有类似特征&#xff0c;而要实现这个功能需要依靠android.widget.AutoCompleteTextView完毕&#xff0c;此类的继承结构例如以下&#xff1a; java.lang.Object↳ android.view.View↳ android.widget…

微信小程序动态设置 tabBar

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 使用微信提供的API wx.setTabBarItem(Object object) 动态设置 tabBar 某一项的内容 参数 Object object 属性类型默认值必填说明indexnumber 是tabBar 的哪一项&#xff0c;从左边算起textstring 否…

NodeJS入门--环境搭建 IntelliJ IDEA

NodeJS入门–环境搭建 IntelliJ IDEA 本人也刚开始学习NodeJS&#xff0c;所以以此做个笔记&#xff0c;欢迎大家提出意见。 1、首先 下载安装NodeJS&#xff0c;下载安装IntelliJ IDEA2、接下来我们详细介绍在IDEA中配置NodeJS 默认安装好了IDEA&#xff0c;在IDEA的file ->…