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

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

问题描述

Spring有两种DI:setter DI和construction DI.

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

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

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

基于 Setter 的 DI 帮助我们仅在需要时才注入依赖项,而不是在构建时才需要.

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

我没有看到任何其他显着差异,因为两种类型的 Spring DI 都提供了相同的特性——setter 和构造函数 DI 在代码启动时注入依赖项.诚然,constructor DI 会通过constructor 来完成,而setter DI 会在构造对象后立即通过setter 来完成,但它在性能等方面对开发者没有任何影响.两者都提供了指定顺序的方法依赖注入也是如此.

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.

我正在寻找一种场景,其中一种类型比另一种类型具有明显优势,或者一种类型完全无法使用.

推荐答案

谈到 Spring 的特定利弊:

When it comes to Spring specific pros and cons:

  • 构造函数注入(根据定义)不允许您在 bean 之间创建循环依赖关系.这个限制实际上是构造函数注入的一个优势——当使用 setter 注入时,Spring 可以解决循环依赖,而你甚至没有注意到.

  • 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.

另一方面,如果您使用构造函数注入,CGLIB 无法创建代理,迫使您要么使用基于接口的代理,要么使用虚拟的无参数构造函数.请参阅:SPR-3150

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

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

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