Setter DI与Spring中的构造函数DI? [英] Setter DI vs. Constructor DI in Spring?

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

问题描述

Spring有两种类型的DI:设置器DI和构造DI。



基于构造函数的DI修复了依赖关系需要注入的顺序。基于Setter的DI不提供此功能。



基于Setter的DI可帮助我们仅在需要时注入依赖关系,而不是在施工时需要。 p>

我没有看到任何其他显着的差异,因为这两种类型的Spring DI提供了相同的功能 - 当代码启动时,设置器和构造函数DI都会注入依赖关系。授权,构造函数DI将通过构造函数执行,而setter DI将在构造对象之后通过设置器进行操作,但在开发人员的性能等方面没有任何差异。两者还提供了指定顺序的方法的依赖注入。



我正在寻找一个场景,其中一个比另一个提供了明显的优势,或者一种类型完全不可用。 strong>

解决方案

当谈到Spring的具体利弊:




  • 构造方法注入(从定义)不允许在bean之间创建循环依赖关系。实际上这种限制实际上是构造函数注入的一个优点 - 当你使用setter注入时,Spring可以解决循环依赖关系,而不需要注意。


  • 另一方面,如果你使用构造函数注入CGLIB无法创建代理,强制您使用基于接口的代理或虚拟非参数构造函数。请参阅: SPR-3150



Spring has two two types of DI: setter DI and construction DI.

Constructor-based DI fixes the order in which the dependencies need to be injected. Setter based DI does not offer this.

Setter-based DI helps us to inject the dependency only when it is required, as opposed to requiring it at construction time.

I do not see any other significant differences, as both types of Spring DI provide the same features - both setter and constructor DI inject the dependency when the code starts up. Granted, constructor DI will do it through the constructor while setter DI will do it through a setter right after constructing the object, but it does not make any difference for the developer in terms of performance, etc. Both also offer means to specify the order of dependency injection as well.

I'm looking for a scenario where one provides a distinct advantage over the other or where one type is completely unusable.

解决方案

When it comes to Spring specific pros and cons:

  • Constructor injection (from the definition) does not allow you to create circular dependencies between beans. This limitation is actually an advantage of constructor injection - Spring can resolve circular dependencies when setter injection is used without you even noticing.

  • On the other hand if you use constructor injection CGLIB is not able to create a proxy, forcing you to either use interface-based proxies or a dummy no-arg constructor. See: SPR-3150

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

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