Spring 抽象类和接口的依赖注入

Spring 抽象类和接口的依赖注入,spring,dependency-injection,Spring,Dependency Injection,我们可以像下面给定的代码那样,将抽象类和接口属性的依赖项注入到我们想要的类中吗 abstract class Parent { } interface Heritage { } class Child { @Autowired private Parent parent; @Autowired private Heritage heritage; } 防止使用属性注入(又称Setter注入)或字段注入注入依赖项。这些做法导致了严重的后果。相反,您应该单独使用构造函数注入作为

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

abstract class Parent { }

interface Heritage { }

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

防止使用属性注入(又称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;
    }
}

当然,只要在上下文中定义了一些实例。抽象毕竟是DI()的一种,用于解耦、可重用性、可测试性、可维护性等。现在,如果您能给我们一些关于您的案例的详细信息,我们可以讨论您试图实现的是否是最好的方式。。。