构造函数注入与二传手注入 [英] Constructor Injection vs Setter Injection

查看:117
本文介绍了构造函数注入与二传手注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读以下内容,作为构造函数和setter注入之间的区别之一。有人可以用一个简单的例子解释以下区别,我对术语全功能对象和不完整对象感到有些困惑。

I have read the following as one of the difference between constructor and setter injection. Can someone explain the below difference with some simple example, I'm bit confused with the term fully function object and incomplete object.

->构造函数DI允许创建对象处于完全状态并遵循功能完善的对象的原理,而Setter DI允许创建对象而无需依赖它。如果依赖项不可用,则可能导致对象不完整

-> Constructor DI allows object to be created in complete state and follows principle of fully functional object while Setter DI allows object to be created without its dependency. which may result in incomplete object if dependency is not available.

推荐答案

使用构造函数时注入,所有必需的依赖项都应该通过构造函数提供,因为应该没有任何设置器,以后才能注入它们。因此,实例具有所有必需的依赖项!

When using Constructor Injection, all required dependencies should be provided through the constructor, as there should not be any setter, to inject them later on. So the instance has all required dependencies!

有了 Setter Injection ,创建实例可能就在那里了,但是没有所有必需的依赖项(因为它们尚未通过设置器设置)。用户可以使用该对象而无需设置必需的依赖项。

With Setter Injection, the create instance might be there, but without all the required dependencies (as they have not been set through the setter). A user can use the object without setting de required dependencies.

另请参见通过构造函数或属性设置器进行依赖注入?

这篇关于构造函数注入与二传手注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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