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() {
[Link] = new Engine(); // tight coupling
public void drive() {
[Link]();
[Link]("Car is driving");
With IoC (Spring Framework)
----------------------------
[Link]
-----------
public class Engine {
public void start() {
[Link]("Engine started");
[Link]
--------
public class Car {
private Engine engine;
// Constructor Injection
public Car(Engine engine) {
[Link] = engine;
public void drive() {
[Link]();
[Link]("Car is driving");
[Link]
---------
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<bean id="engine" class="Engine" />
<bean id="car" class="Car">
<constructor-arg ref="engine"/>
</bean>
</beans>
[Link]
---------
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("[Link]");
Car car = (Car) [Link]("car");
[Link]();