首页 > 解决方案 > 抽象类和接口的依赖注入

问题描述

我们可以像下面给出的代码那样将抽象类和接口属性的依赖注入到我们想要的类中吗?

abstract class Parent { }

interface Heritage { }

class Child
{
    @Autowired private Parent parent;
    @Autowired private Heritage heritage;
}

标签: springdependency-injection

解决方案


使用属性注入(又名 Setter 注入)或字段注入来防止注入依赖项。这些做法导致了时间耦合。相反,您应该只使用构造函数注入作为 DI 的实践,因为:

  • 构造函数可以保证提供所有依赖项,防止时间耦合
  • 构造函数静态声明类的依赖项
  • 允许创建类的实例而不需要任何工具(例如 DI 容器)来构造该类型
  • 当一个组件只有一个构造函数时(这是一种很好的做法),它可以避免使用任何特殊的框架特定属性来标记类,例如@Autowired.

使用构造函数注入时,该类将如下所示:

class Child
{
    private Parent parent;
    private Heritage heritage;

    public Child(Parent parent, Heritage heritage) {
        if (parent == null) throw new NullErrorException();
        if (heritage == null) throw new NullErrorException();

        this.parent = parent;
        this.heritage = heritage;
    }
}

推荐阅读