Spring Tutorial: Dependency Injection

Dependency Injection is also one of the core concepts of Spring Framework. It is a design pattern that removes the dependency from the code. That is, the Spring Framework provides the dependencies of the class itself so that it can be easy to manage and test the application. You can provide information from external source such as XML file. Here, you do not create the objects instead you just define how they should be created and IoC container will create the objects for you.

In Spring, dependencies can be injected in two ways:

  1. By constructor
  2. By setter method

Lets see how they are done.

By Constructor

  • The <constructor-arg> subelement of <bean> is used for constructor injection.
  • By default when the Spring container loads the bean, it instantiates the bean with the default constructor. But you can also define a constructor argument in bean definition, using an argument constructor.

By setter method

  • The <property> subelement of <bean> is used for setter injection.
  • Setter-based Dependency Injection is accomplished by the container calling setter methods on your beans after invoking a no-argument.