This article will explain how Sprint Boot framework achieve IoC , inverstion of control via DI , dependency injection.
However pickocode has explained how traditional Java program work with and without DI. If you want to watch that follow below URL.
Dependency Injection
Subscribe our YouTube channel for more tutorial with programming examples.
https://www.youtube.com/channel/UCiP3dlCCZ2Sx6CUyQ7W_vaw?view_as=subscriber
In traditional programming what we are doing is we create an interface and an implemented class. Then out side class will invoke that implemented class (s) with new keyword and working with rest of the things. You can go to this article if want to know how traditional Java achieved IoC principal using DI design pattern.
Now lets get back to the topic , how spring boot achieve DI .
Spring boot DI can be achieved using following ways.
- Constructor DI
- Setters DI
- Fields DI
Constructor Dependency Injection
From the constructor we can invoke dependencies what we need. Check below example how to achieve constructor dependency. You may heard about Beans annotation and Configuration annotation in sprint. Where @Configuration tells that this class is for defining beans. Where @bean annotation defines a bean. Moreover when we create a bean it act as a singleton object, only one object per project.
@Configuration
public class CarConfig{
@Bean
public Engine v6Engine() {
return new V6EngineImpl();
}
@Bean
public Car cefiro() {
return new Car(v6Engine());
}
}
Setter Dependency Injection
Container can link the perticular bean from setter methods
@Bean
public Car cefiro() {
Car cefiroCar = new Car ();
cefiroCar.setEngine(v6Engine());
return cefiroCar ;
}
Field based Dependency Injection
Simply we can link and invode a bean from a property
public class Car{
@Autowired
private Engine v6Engine;
}