Monday, November 27, 2017

Different Types of Bean Injection in Spring

1. Overview

In this tutorial, we’re going to take a first look at the Different Types of Bean Injection in Spring.
Spring framework is eminent for its implementation of Inversion of Control (IoC) principle that is also called Dependency Injection (DI). It's the best feature is loosely coupled and reusable beans, an object managed by Spring. More specifically, it can be instantiated, configured and otherwise managed by a Spring Framework container. Beans are defined in a Spring configuration file (or by using annotations), instantiated by the Spring container, and then injected into our application.

2. Characteristics of Dependency Injection

i) DI is where a needed dependency is injected by another object.
ii) The class being injected has no responsibility in instantiating the object being injected.
iii) Avoid declaring object using [new]

3.  Types of Dependency Injections

There are 3 types of dependency injection.
i) By Property
ii) By Setter
iii) By Constructor
By Constructor is favored most. It requires the dependency to be injected when the class is instantiated.

By Setter:
The <property> sub-element of <bean> is actually used for setter injection. Here,
i) property element invokes the setter method.
ii) value sub-element of a property will assign the specified value.

By Constructor:
Constructor based injection defines bean dependencies via constructor as one or more constructor arguments, which are injected by the container at the time of bean creation. It can be defined via XML based configuration as the following section:

 <bean id="person"
  class="com.spring.tutorial.Person">
  <constructor-arg value="6012" name="id" type="int">
  </constructor-arg>
  <constructor-arg value="Zakir" name="name" type="String"></constructor-arg>
  <property value="224498" name="nationalId">
  </property>
  <property name="address" ref="address"></property>
 </bean>

 <bean id="address" class="com.spring.tutorial.Address">
  <constructor-arg name="street" value="1 Jessore Benapole Lane"></constructor-arg>
  <constructor-arg name="postcode" value="7432"></constructor-arg>
 </bean>

Spring support Dependency Injection against a private property. For this, it requires injecting the dependency using reflection at run-time. However, this is considered a VERY bad practice.

Resource Link:

4.  Why we choose constructor Injection?

Oliver Gierke has shown the real cause of choosing constructor Injection in this tutorial: Why field injection is evil?


5.  Conclusion

All the code of this article is available over on Github. This is a Maven-based project, so it should be easy to import and run as it is.

No comments:

Post a Comment