依赖注入:Spring和Java

时间:2016-10-10 19:51:58

标签: java spring dependency-injection

我最近开始使用Spring Framework。 在一本书中,我找到了这个例子:

public class DamselRescuingKnight implements Knight {

   private RescueDamselQuest quest;

   public DamselRescuingKnight() {
      this.quest = new RescueDamselQuest();
   }

   public void embarkOnQuest() {
      quest.embark();
   }
}

使用Spring Constructor Dependency Injection,示例变为:

public class DamselRescuingKnight implements Knight {

   private Quest quest;

   public DamselRescuingKnight(Quest quest) {
      this.quest = quest;
   }

   public void embarkOnQuest() {
      quest.embark();
   }
}

xml文件配置为:

<bean id="knight" class="com.springinaction.knights.DamselRescuingKnight">
   <constructor-arg ref="quest" />
</bean>

<bean id="quest" class="com.springinaction.knights.somethingThatImplementsQuest">
</bean>

为了完全理解这个概念, 你能用 only Java (没有Spring,没有xml文件)编写相同类的依赖注入的替代示例吗?

1 个答案:

答案 0 :(得分:2)

这相当于配置文件中的依赖项注入。唯一的区别是您的Quest对象是在BraveKnight实例之后创建的。

public class BraveKnight {
    private Quest quest;
    public BraveKnight(Quest quest) {
        this.quest = quest;
    }
}

public class Quest {

}

public class Main {
    public static void main (String[] args) {
        Quest quest = new Quest();
        BraveKnight knight = new BraveKnight(quest);
    }
}