Spring-Spring Core1 Comment

In Spring, IOC- Dependency Injection (DI) is a process whereby objects define their dependencies, one of the main functional and we will used it alots. In this post I will show you 2 types of DI :

  1. Setter Injection
  2. Constructor Injection

If you dont know how to create the bean with spring or prepare maven to start. You might want to check this post first Spring HelloWorld

  • Setter Injection

This is the most popular and simple DI method, it will injects the dependency via a setter method.

Here is Car class with a Fuel setter, we will need fuel injected to Car ( otherwise you will have to call the rescue car  service ^^)

Car :

Fuel :

A bean configuration file to declare the beans and set the dependency via setter injection (property tag).

spring-core.xml : 

You just injected fuel bean into car object via a setter method (setFuel), your car will run very fast now ^^.

  • Constructor Injection

Look back to our previous example, this time, we want all car need to have full fuel whenever their objects are created. All we need is a constructor :

Car :

A bean configuration file to declare the beans and set the dependency via constructor injection (constructor-arg tag).

spring-core.xml : 

Almost look the same, right ? We will talk what they are different each other in another post.

  • Setter or Constructor Injection ?

There are no hard rule set by Spring framework, just use whatever type of DI that suit your project needs. However, due to the simplicity of the setter injection, it’s always selected for most of the scenarios.

 

 

 


1 Comment on this article

Add a comment