Lesson

Spring Dependency Injection

spring/Spring Boot

Dependency Injection (DI)

Introduction

In this tutorial, you will learn:

  • What is Dependency Injection

  • Why DI is important

  • Types of DI

  • Real example (Engine + Vehicle)

  • Setter Injection

  • Constructor Injection

What is Dependency Injection?

Dependency Injection means:

A class does not create its own objects.
Spring provides the required objects.

Simple Definition

Instead of:

Vehicle creates Engine

We do:

Spring injects Engine into Vehicle

Why Dependency Injection?

Problems without DI

  1. Tight Coupling
    One class depends strongly on another class

  2. Hard Testing
    Cannot easily use mock objects

  3. Poor Maintainability
    Changes required in multiple places

  4. Less Flexibility
    Cannot switch implementation easily

Types of Dependency Injection

There are mainly two types:

1. Setter Injection

2. Constructor Injection

Example

We will create:

  • Interface: IEngine

  • Class: ToyotaEngine

  • Class: Vehicle

Step 1: Create Interface

java
public interface IEngine {
    void start();
}

Step 2: Create Implementation

plaintext
public class ToyotaEngine implements IEngine {

    @Override
    public void start() {
        System.out.println("Toyota Engine started");
    }
}

Step 3: Create Dependent Class

plaintext
public class Vehicle {

    private IEngine engine;

    // Constructor DI
    public Vehicle(IEngine engine) {
        this.engine = engine;
    }

    // Setter DI
    public void setEngine(IEngine engine) {
        this.engine = engine;
    }

    public void drive() {
        engine.start();
        System.out.println("Vehicle is moving");
    }
}

Constructor Dependency Injection

XML Configuration

plaintext
<bean id="engine" class="ToyotaEngine"/>

<bean id="vehicleConstructor" class="Vehicle">
    <constructor-arg ref="engine"/>
</bean>

Key Points

  • Dependency passed at object creation

  • Object becomes immutable

  • Best for required dependencies

Setter Dependency Injection

XML Configuration

plaintext
<bean id="vehicleSetter" class="Vehicle">
    <property name="engine" ref="engine"/>
</bean>

Key Points

  • Dependency set after object creation

  • Mutable object

  • Optional dependency

Main Class

plaintext
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

    public static void main(String[] args) {

        ApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        Vehicle v1 = (Vehicle) context.getBean("vehicleConstructor");
        v1.drive();

        Vehicle v2 = (Vehicle) context.getBean("vehicleSetter");
        v2.drive();
    }
}

Output

plaintext
Toyota Engine started
Vehicle is moving
Toyota Engine started
Vehicle is moving

Setter Injection

  • Can change dependency later

  • Not mandatory

  • Less strict

Constructor Injection

  • Mandatory dependency

  • More secure

  • Better for testing

  • Recommended in Spring Boot

Spring Boot Version (Modern Way)

In Spring Boot, we use annotations instead of XML.

Example

java
@Component
public class ToyotaEngine implements IEngine {
    public void start() {
        System.out.println("Toyota Engine started");
    }
}
java
@Component
public class Vehicle {

    private final IEngine engine;

    @Autowired
    public Vehicle(IEngine engine) {
        this.engine = engine;
    }

    public void drive() {
        engine.start();
        System.out.println("Vehicle is moving");
    }
}

Final Summary

  • DI = Spring injects dependencies

  • Removes tight coupling

  • Improves testing and flexibility

  • Constructor Injection is best practice

  • Spring Boot uses annotations

"Dependency Injection in Spring allows objects to receive dependencies from the IoC container instead of creating them manually, which helps achieve loose coupling and better maintainability."

BeanFactory vs ApplicationContext in Spring

1. Introduction

In the Spring Framework, the IoC (Inversion of Control) container is responsible for:

  • Creating objects (beans)

  • Managing dependencies

  • Configuring the application

Spring provides two main types of containers:

  • BeanFactory (basic container)

  • ApplicationContext (advanced container)

2. BeanFactory

BeanFactory is the basic IoC container in Spring.

Package:

plaintext
org.springframework.beans.factory

Key Features

  • Creates beans only when required

  • Uses lazy initialization

  • Lightweight container

  • Suitable for small or memory-constrained applications

Example

plaintext
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

BeanFactory factory = new XmlBeanFactory(
    new ClassPathResource("beans.xml"));

MyBean obj = (MyBean) factory.getBean("myBean");

Important Note

  • XmlBeanFactory is deprecated (Spring 3.1) and removed in Spring 4.0

  • In real projects, BeanFactory is rarely used directly


3. ApplicationContext

ApplicationContext is an advanced container that extends BeanFactory.

Package:

plaintext
org.springframework.context

Key Features

  • Uses eager initialization (default)

  • Supports annotations

  • Provides event handling

  • upports internationalization (i18n)

  • Automatically handles post-processors

plaintext
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

ApplicationContext context =
    new ClassPathXmlApplicationContext("beans.xml");

MyBean obj = context.getBean("myBean", MyBean.class);

4. Difference Between BeanFactory and ApplicationContext

Definition

  • BeanFactory: Basic container for managing beans

  • ApplicationContext: Advanced container with extra features

Usage

  • BeanFactory: Small standalone applications

  • ApplicationContext: Enterprise and web applications

Bean Initialization

  • BeanFactory: Lazy initialization (on demand)

  • ApplicationContext: Eager initialization (on startup)

Bean Scopes

  • BeanFactory: Singleton, Prototype

  • ApplicationContext: Singleton, Prototype, Request, Session, etc.

Annotation Support

  • BeanFactory: XML-based configuration only

  • ApplicationContext: Supports annotations

Internationalization

  • BeanFactory: Not supported

  • ApplicationContext: Supported using MessageSource

Event Handling

  • BeanFactory: Not supported

  • ApplicationContext: Supported using events

Bean Post Processing

  • BeanFactory: Manual configuration required

  • ApplicationContext: Automatic

Resource Usage

  • BeanFactory: Less memory usage

  • ApplicationContext: More features, slightly higher memory usage


5. Conclusion

  • BeanFactory is simple and lightweight but rarely used in modern applications

  • ApplicationContext is powerful and widely used in Spring Boot and enterprise projects