Inversion_of_Control_with_Example
Inversion_of_Control_with_Example
Definition:
Inversion of Control is a principle in which the control of object creation and dependency
management is transferred from the program to a container or framework. In Spring, the IoC
Example:
------------------------------------
public Car() {
engine.start();
System.out.println("Car is driving");
----------------------------
Engine.java
-----------
System.out.println("Engine started");
Car.java
--------
// Constructor Injection
this.engine = engine;
engine.start();
System.out.println("Car is driving");
beans.xml
---------
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<constructor-arg ref="engine"/>
</bean>
</beans>
Main.java
---------
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
car.drive();