In Spring, Inversion of Control(IOC) is implemented using Dependancy Injection(DI) Design Pattern. Let's understand DI with java example and then I will see how DI can solve tightly coupled problem and Spring container will inject dependency.
What is Inversion of Control?
IOC allows you to decouple your program into separate components that don't know each other. supposed if I have two classes which implements common interface then In order to use, In my Java class i need to create instance of those classes. which looks like tightly coupled.
If we can define which class to use at runtime using Injecting dependency at runtime then it will be good , right? This is where IOC comes to Picture.
Concept IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection.
There are three forms or styles of Dependency Injection.
1.Constructor Injection
2.Setter Injection
3.Interface Injection
1. Constructor Injection: Here, IoC container uses the constructor to inject the dependency. Since All dependencies are declared in one constructor, it's added advantage.
- here, handling over dependencies takes during instantiation of the dependent object.
2. Setter Injection: Here, DI uses Setters to inject the required resources or dependencies.Meaning class will have setters, the IoC container will use the setters to provide the resource at run-time.
- here, handling over dependencies takes after the dependent object is instantiated
What is Inversion of Control?
IOC allows you to decouple your program into separate components that don't know each other. supposed if I have two classes which implements common interface then In order to use, In my Java class i need to create instance of those classes. which looks like tightly coupled.
If we can define which class to use at runtime using Injecting dependency at runtime then it will be good , right? This is where IOC comes to Picture.
Concept IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection.
There are three forms or styles of Dependency Injection.
1.Constructor Injection
2.Setter Injection
3.Interface Injection
1. Constructor Injection: Here, IoC container uses the constructor to inject the dependency. Since All dependencies are declared in one constructor, it's added advantage.
- here, handling over dependencies takes during instantiation of the dependent object.
2. Setter Injection: Here, DI uses Setters to inject the required resources or dependencies.Meaning class will have setters, the IoC container will use the setters to provide the resource at run-time.
- here, handling over dependencies takes after the dependent object is instantiated