Inversion of Control (IoC) in Spring
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
container manages the lifecycle and configuration of application objects.
Example:
Without IoC (Manual Object Creation)
------------------------------------
public class Car {
private Engine engine;
public Car() {
this.engine = new Engine(); // tight coupling
public void drive() {
engine.start();
System.out.println("Car is driving");
With IoC (Spring Framework)
----------------------------
Engine.java
-----------
public class Engine {
public void start() {
System.out.println("Engine started");
Car.java
--------
public class Car {
private Engine engine;
// Constructor Injection
public Car(Engine engine) {
this.engine = engine;
public void drive() {
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">
<bean id="engine" class="Engine" />
<bean id="car" class="Car">
<constructor-arg ref="engine"/>
</bean>
</beans>
Main.java
---------
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Car car = (Car) context.getBean("car");
car.drive();