Inversion Of Control


Inversion of Control (IoC) is a design pattern that enables loose coupling between components in an application. It is the foundation of the Spring Framework and is implemented through the use of Dependency Injection (DI). The basic idea behind IoC is that instead of an object creating its own dependencies, it receives them from an external source. This makes your code more modular and easier to test.

Here is an example to help illustrate the concept of IoC:

public class MyService {
    private MyDao myDao;

    public MyService() {
        myDao = new MyDao();
    }

    public void doSomething() {
        myDao.saveData("Hello, world!");
    }
}

public class MyDao {
    public void saveData(String data) {
        System.out.println("Saving data: " + data);
    }
}

In this example, we have two classes: MyService and MyDao. MyService creates a new instance of MyDao within its constructor and uses it to perform a save operation.

Now, let’s consider a scenario where we want to replace the MyDao class with a different implementation. We would need to modify the MyService class to use the new implementation, which could lead to tightly-coupled code and a maintenance nightmare.

With IoC, we can avoid this issue by using Dependency Injection to inject the MyDao object into the MyService class, like this:

public class MyService {
    private MyDao myDao;

    public MyService(MyDao myDao) {
        this.myDao = myDao;
    }

    public void doSomething() {
        myDao.saveData("Hello, world!");
    }
}

public class MyDao {
    public void saveData(String data) {
        System.out.println("Saving data: " + data);
    }
}

In this example, we have modified the MyService constructor to take a MyDao object as a parameter. This object is then used to perform the save operation. By doing this, we have decoupled the MyService and MyDao classes, and we can easily replace the MyDao object with a different implementation without having to modify the MyService class.

This is the essence of IoC. Instead of objects creating their own dependencies, they receive them from an external source. This makes your code more modular, easier to test, and less prone to tight coupling and maintenance issues.

A quick recap of java