spring Dependency Injection (DI) and Inversion of Control (IoC) Injecting a dependency manually through XML configuration


Example

Consider the following Java classes:

class Foo {
  private Bar bar;

  public void foo() {
    bar.baz();
  }
}

As can be seen, the class Foo needs to call the method baz on an instance of another class Bar for its method foo to work successfully. Bar is said to be a dependency for Foo since Foo cannot work correctly without a Bar instance.

Constructor injection

When using XML configuration for Spring framework to define Spring-managed beans, a bean of type Foo can be configured as follows:

<bean class="Foo">
  <constructor-arg>
    <bean class="Bar" />
  </constructor-arg>
</bean>

or, alternatively (more verbose):

<bean id="bar" class="bar" />

<bean class="Foo">
  <constructor-arg ref="bar" />
</bean>

In both cases, Spring framework first creates an instance of Bar and injects it into an instance of Foo. This example assumes that the class Foo has a constructor that can take a Bar instance as a parameter, that is:

class Foo {
  private Bar bar;

  public Foo(Bar bar) { this.bar = bar; }
}

This style is known as constructor injection because the dependency (Bar instance) is being injected into through the class constructor.

Property injection

Another option to inject the Bar dependency into Foo is:

<bean class="Foo">
  <property name="bar">
    <bean class="Bar" />
  </property>
</bean>

or, alternatively (more verbose):

<bean id="bar" class="bar" />

<bean class="Foo">
  <property name="bar" ref="bar" />
</bean>

This requires the Foo class to have a setter method that accepts a Bar instance, such as:

class Foo {
  private Bar bar;

  public void setBar(Bar bar) { this.bar = bar; }
}