TIL: Dependency Injection / Inversion of Control

adamsteradam·2022년 9월 30일

What is Dependency Injection (DI) and Inversion of Control(IoC)?

By definition, IoC is when objects do not create other objects on which they rely to do their work, instead they get the objects from outside.
Think of it as "lamp" and the outlet. We don't directly connect the lamp to the outlet but we plugin the lamp to the outlet to get the electricity.
"Dependency = new keyword ()"

Benefits of IOC

  1. Reduces amount of application code

  2. Decreases coupling between classes

  3. Makes the application easier to test and maintain


public class Student {
    private String name;
    public Student(String name) {
        this.name = name;
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;
<bean id="student">
  <constructor-arg index="0" value="Adam"></constructor-arg>

What is Dependency Injection?

DI is when passing a dependent object as a parameter to a method rather than having the method create the dependent object.

  • Method does not have a direct dependency on a particular implementation.
  • Any implementation satisfying requirements can be passed as a parameter.
    Example: Database
    • as long as the database meets the requirements, it does not matter which database is chosen, Spring will configure it.

      "Rely on abstraction rather than concrete implementation"

DI Flow

Also, in order to implement DI, we need classes that fulfill these roles:
1. The service you want to use.
2. The client that uses the service.
3. An interface that’s used by the client and implemented by the service.
4. The injector which creates a service instance and injects it into the client.

0개의 댓글