Spring 自动装配 setter/constructor 的优点和缺点
当使用@Autowired(不是xml配置)时,有人可以比较set/constructor绑定的优缺点吗?
请参阅以下示例:
public class Example{
private Logger log;
// constructor wiring
@Autowired
public Example(Logger log){
this.log = log;
}
}
public class Example{
// setter wiring
@Autowired
private Logger log;
}
When using @Autowired (not xml configuration), could someone compare the set/constructor binding advantages and disadvantages?
See the following examples:
public class Example{
private Logger log;
// constructor wiring
@Autowired
public Example(Logger log){
this.log = log;
}
}
public class Example{
// setter wiring
@Autowired
private Logger log;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这完全是一个偏好问题。
Spring 不赞成构造函数注入,或者至少习惯于这样做,因为这样会出现循环依赖关系,并且它们很难管理(A 在构造函数中需要 B,B 在构造函数中需要 A)。
一个实际的区别是,在字段上使用 @Autowired 时,您不需要 setter 方法,这一方面使类更小且更易于阅读,但另一方面使得模拟类有点丑。
我更喜欢现场注入。
It is entirely a matter of preference.
Spring frowns upon constructor injection, or at least used to, because thus circular dependencies appear and they are hard to manage (A needs B in constructor, B needs A in constructor).
One actual difference is that with
@Autowired
on a field you don't need a setter method, which, on one hand makes the class smaller and easier to read, but on the other hand makes mocking the class a bit uglier.I prefer the field injection.
在每个人都投票支持字段注入很久之后,我们仍然扮演魔鬼倡导者的角色,这里有一些使用从周围同事投票中收集的构造函数的优点:
我仍然喜欢这样一个事实:如果我需要另一个类中的带注释的字段,我可以只进行复制粘贴并完成它,而不是添加它对于构造函数来说,但这只是次要考虑因素。
Playing the devil advocate long after everyone voted for field injection, here are some advantages for using constructors gathered from polling coworkers around:
I still like the fact that if I need an annotated field in another class, I can just do a copy-paste and be done with it as opposed to adding it to the constructor, but it is only a secondary consideration.
对 setter 进行注释的具体原因是:setter 可以将 bean 引用保存到静态变量。
A specific reason for annotating setters: The setters can then save bean references to static variables.
如果您没有使用自动装配,则构造函数注入和设置器注入之间存在很大差异。您可以以不同的方式编写 XML 以注入依赖项。 setter 注入依赖项是可选的,而构造函数注入依赖项不是可选的。
对于自动装配,我能想到的唯一原因是避免循环依赖问题。如果 A 的 B 对构造函数有自动装配的依赖关系,而 B 对 A 也有相同的依赖关系,那么我们就无法实例化它们中的任何一个。给一个 setter 依赖可能会有所帮助。
If you weren't using autowiring, there is a big difference between constructor and setter injection. You write the XML differently in order to inject the dependencies. And setter injection dependencies are optional while constructor injection dependencies are not.
With autowiring, the only reason I can think of is to avoid a circular dependency problem. If A has B has an autowired dependency to the constructor and B has the same for A, we can't instantiate either of them. Giving one a setter dependency could help with that.