解释为什么构造函数注入比其他选项更好 [英] Explain why constructor inject is better than other options
问题描述
在Pro Spring 3 Book中,
第4章 - 介绍IOC和DI在春天 - 第59页,在Setter Injection vs. Constructor Injection部分,一段说明
In a Pro Spring 3 Book, Chapter 4 - Introduction IOC and DI in Spring - Page 59, In "Setter Injection vs. Constructor Injection" section, a paragraph says
包含Spring,提供了一种机制,用于确保在
使用Setter Injection时定义所有依赖项,但是通过使用Constructor Injection,您可以声明对依赖项的要求与容器无关的方式
Spring included, provide a mechanism for ensuring that all dependencies are defined when you use Setter Injection, but by using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner"
你能用例子解释
推荐答案
只有提供了该参数才能实例化一个必需的依赖项作为构造函数参数的类(你应该有一个guard子句来确保参数不为null。)因此构造函数强制执行依赖性要求是否使用Spring,使其与容器无关。
A class that takes a required dependency as a constructor argument can only be instantiated if that argument is provided (you should have a guard clause to make sure the argument is not null.) A constructor therefore enforces the dependency requirement whether or not you're using Spring, making it container-agnostic.
如果使用setter注入,则可能会也可能不会调用setter,因此实例可能永远不会提供d依赖它。强制调用setter的唯一方法是使用 @Required
或 @Autowired
,这是特定于Spring,因此不与容器无关。
If you use setter injection, the setter may or may not be called, so the instance may never be provided with its dependency. The only way to force the setter to be called is using @Required
or @Autowired
, which is specific to Spring and is therefore not container-agnostic.
因此,为了保持代码独立于Spring,请使用构造函数参数进行注入。
So to keep your code independent of Spring, use constructor arguments for injection.
更新:Spring 4.3将执行单构造函数场景中的隐式注入,使您的代码更加独立于Spring,可能不需要 @Autowired
注释。
Update: Spring 4.3 will perform implicit injection in single-constructor scenarios, making your code more independent of Spring by potentially not requiring an @Autowired
annotation at all.
这篇关于解释为什么构造函数注入比其他选项更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!