Dependency Injection in Spring, Introduction and types

Definition of Dependency Injection in Spring

Dependency Injection is a software engineering pattern in which a dependent object is passed on to the client by an external agency such as the Spring container. Dependency Injection is one way to achieve Inversion of Control since the control of creating the Objects is not with the client but with the framework.

Why Dependency Injection?

The most obvious question is why do we want this inversion of control. What is so wrong with the client itself maintaining the state of the object?
well, there are multiple advantages to dependency injection in Spring. Here are some of them.

Advantages of Dependency Injection in Spring

  • The container manages the lifecycle of the object so each client does not have to know how to create or destroy the object.
  • The container can be specified to create a single instance of the object and pass that around or create a separate instance for each client.
  • Since the container creates all objects, it can also pass these objects to the constructor of other objects. This saves the client from maintaining the complete dependency tree for all object it creates. For example, if class A needs class B and class C in its constructor then the client does not need to know about class B and class C at all if the container manages class A and its creation.
    Dependency Injection in Spring

These are only some of the advantages of dependency injection in spring and as you go through various other tutorials you will learn how dependency injection is the main backbone over which Spring framework has been designed.

Types of Dependency Injection in Spring

There are two main types of dependency injections in spring and one other less used type.

Constructor based injection

In spring Constructor injection the dependent objects are injected into the client using the client’s constructor. this tutorial looks into more details into the constructor injection.

Setter based injection

In this type of injection, the dependencies are injected after the client object has been created. The dependencies are injected using the setter method of the client. This tutorials looks into details of Setter injection.

Inner Bean

Another indirect form of dependency injection is using inner beans. This is where a bean is defined inside another bean. Look at this tutorial on inner beans for more details.

In the next tutorials, we will look at examples of the different types of dependency injections with examples.

Leave a Comment