弹簧自动装配器/构造器的优点和缺点 [英] Spring autowiring setter/constructor PROs and CONs

查看:156
本文介绍了弹簧自动装配器/构造器的优点和缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用@Autowired(不是xml配置)时,有人可以比较set/constructor绑定的优点和缺点吗?

When using @Autowired (not xml configuration), could someone compare the set/constructor binding advantages and disadvantages?

请参阅以下示例:

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;
}

推荐答案

这完全是优先事项.

在构造函数注入时,Spring会皱眉,或者至少是不习惯的,因为这样会出现循环依赖关系,并且难以管理(A在构造函数中需要B,B在构造函数中需要A).

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

一个实际的区别是,在字段上使用@Autowired时,您不需要setter方法,该方法一方面使类更小且更易于阅读,但另一方面使类的模仿变得更丑陋

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.

我更喜欢现场注入.

这篇关于弹簧自动装配器/构造器的优点和缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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