依赖注入如何工作? [英] How is dependency injection working?

查看:137
本文介绍了依赖注入如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Pro Spring 2.5一书,我对依赖注入如何工作有疑问。

I am reading the Pro Spring 2.5 book and I have a question to how dependency injection works.

我理解BeanFactory并进行依赖查找。现在我读到依赖注入,我有一些问题。根据我的理解,您希望将查找限制到最小,例如查找对象以启动应用程序。然后依赖注入将处理其余的事情。但是我不明白这是有效的。

I understand the BeanFactory and doing dependency lookups. Now I read about dependency injection and I have some questions. Based on what I understand you want to limit the lookups to the minimum such as looking up an object for boot strapping the application. Then dependency injection will take care of the rest. However I don't understand this works.

假设你有一个beanfactory,你会得到一个启动整个应用程序的MyApplication实例。其余对象使用依赖注入来获取其协作者。 beanfactory维护它管理的bean列表,但这个工厂不仅仅在应用程序的main方法中可用吗?如果beanfactory还管理其包含bean的范围,我不明白这是怎么做的。 beanfactory在某种程度上是全局的吗?

Let say you have a beanfactory, you get an MyApplication instance that starts the whole application. The rest of the objects use dependency injection to get their collaborators. The beanfactory maintains the list of beans it manages but isn't this factory only available in the main method of the application? And if the beanfactory also manages the scope of their containing beans I don't understand how that is done. Are the beanfactory global in some way?

推荐答案

bean工厂实例化所有对象。它解析您的配置(xml或注释),实例化您的bean并设置它们的依赖项。然后所有这些bean都存储在应用程序上下文中。

The bean factory instantiates all objects. It parses your configuration (xml or annotations), instantiates your beans and sets their dependencies. Then all these beans are stored in the application context.

你通常有一个应用程序的入口点 - 你做 context.getBean(。 。)。现在bean已经注入了它的依赖项,因为它被bean工厂放在上下文中。

You usually have an entry point to your application - there you do context.getBean(..). Now that bean has its dependencies injected, because it is put in the context by the bean factory.

可能会清除事物的经验法则:你从不使用<使用DI框架时code> new 运算符(带有bean类)。框架是实例,而不是你。

The rule of thumb that will probably clear things: you never use the new operator (with bean classes) when using a DI framework. The framework makes the instances, not you.

这篇关于依赖注入如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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