【问题标题】:Difference beetwen that kinds of Dependency Injection依赖注入的区别
【发布时间】:2020-05-20 12:53:02
【问题描述】:

我有一个关于 Spring 中的依赖注入的快速问题。我有两个虚拟类,它们都使用了一点不同的方法,在这里提出了这个问题。哪个更好?为什么?

FIRST APPROACH
public class ClassName {
   private final Object obj;

   public ClassName(Object obj){
      this.obj = obj;
}

SECOND APPROACH
public class ClassName {
   private Object obj;

   @Autowired
   public ClassName(Object obj){
       this.obj = obj;
}

【问题讨论】:

  • 假设这些是@Components(或相关的刻板印象),除了第二个多余的注释之外没有区别。

标签: java spring dependency-injection


【解决方案1】:

两者之间没有区别,因为它们只有一个构造函数。在具有多个构造函数的情况下进行依赖注入时,您应该在构造函数上使用 @Autowired 的唯一情况。例如:

@Component
public class ClassName {
    final Object obj;

    public ClassName() {
        this.obj = null; // null or something else
    }

    @Autowired
    public ClassName(Object obj) {
        this.obj = obj;
    }
}

如果你不在构造函数上使用@Autowired,你打算初始化默认值,那么将选择无参数构造函数。因此,在上述情况下,如果您省略 @Autowired,则 obj 的值将设置为 null

【讨论】:

    猜你喜欢
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 2015-01-09
    • 2016-08-14
    相关资源
    最近更新 更多