Reputation: 294
I recently started to use the Spring Framework. In a book I found this example:
public class DamselRescuingKnight implements Knight {
private RescueDamselQuest quest;
public DamselRescuingKnight() {
this.quest = new RescueDamselQuest();
}
public void embarkOnQuest() {
quest.embark();
}
}
Using Spring Constructor Dependency Injection, the example becomes:
public class DamselRescuingKnight implements Knight {
private Quest quest;
public DamselRescuingKnight(Quest quest) {
this.quest = quest;
}
public void embarkOnQuest() {
quest.embark();
}
}
While the xml file configuration is:
<bean id="knight" class="com.springinaction.knights.DamselRescuingKnight">
<constructor-arg ref="quest" />
</bean>
<bean id="quest" class="com.springinaction.knights.somethingThatImplementsQuest">
</bean>
In order to completely understand the concept, could you write an alternative example of Dependency Injection of the same classes using only Java (without Spring, so without the xml file)?
Upvotes: 1
Views: 253
Reputation: 1308
This is equivalent to the dependency injection from your configuration file. The only difference is that your Quest
object is created after the BraveKnight
instance.
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);
}
}
Upvotes: 2