Constructor Injection

  • It is a bean wiring technique, where an object is provided its dependencies via its own constructors.
  • The dependencies are passed as arguments of the constructors with each representing a property or a collaborator object.
  • In this method, each object declares a constructor or a set of constructors that take object dependencies as arguments.
  • The Spring container will then pass the dependencies to the object, as and when needed.
  • The injection of a value into a bean property can be done with the help of the element, declared within the element inside the configuration file.

The value of the property is set by using the value attribute of the <constructor-arg> element.

For example:

<bean id="ABCDE"
class="SetterInject.FootballPlayer">

<constructor-arg value="7"/>

</bean>

<bean id="PQRS" class="SetterInject.FootballPlayer">

<constructor-arg value="21"/>

</bean>

Now, when ABCDE and PQRS play football, the following output will be displayed:

I am playing with shirt number 7.

I am playing with shirt number 21.