Different ways of Dependency Injection

I explained in my previous post on Spring Framework [Dependency Injection] what is dependency injection? how spring finds the dependency? how does spring create and inject the service? etc. In this continued post, I will try to explain the three different ways of Dependency Injection.

  1. Field  Injection: Using autowired annotation on a field.
  2. Method Injection: Using autowired annotation on a setter method.
  3. Constructor Injection: Using autowired annotation on a constructor.

The order in which the injection takes place is constructor followed by field and then method.

Autowired annotation on a field is explained here in my git hub code [Autowired Dependency] and in the previous Dependency Injection post. In this post, we will cover the setter and constructor dependency injection.

Setter Based Dependency Injection:

It is done by container calling the setter method on your bean after invoking a no argument constructor or a no argument static factory method to instantiate your bean. Example of setter based dependency injection is shown here on my git hub code: Setter DI Example

Constructor Based Dependency Injection:

It is done by container calling the parameterised constructor of the class with each parameter representing the dependency on another class. Example of constructor based dependency injection is shown here on my git hub code: Constructor DI Example Code and Constructor DI Example Test

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s