Dependency Injection in Spring Boot Explained with Examples for Beginners 2026

Author: Ritika
0

 

If you are learning Spring Framework for the first time, one term you will hear again and again is Dependency Injection or simply DI. Honestly, when I first heard this in my 3rd year, it sounded very heavy and complicated. I thought it was some advanced concept only for experienced developers. But once I started building projects using Spring Boot, I realized it’s actually a very practical and simple idea.

 

In most college projects, we write code where one class depends on another class. Like when our service class uses a repository class, or a controller uses a service. Managing these dependencies properly becomes very important when the project grows. Otherwise code becomes messy, tightly connected and very hard to maintain.

 

That’s where Dependency Injection helps.

 

In this blog, I’ll explain DI in a very simple way like how we discuss before exams or during lab practicals. No heavy theory. Just practical understanding with examples.

(toc) #title=(Table of Content)

 

What is Dependency Injection?

Let’s understand this in simple words.

 

Dependency means one class needs another class to work.

Injection means giving that required object from outside instead of creating it inside the class.

 

So,

 

Dependency Injection is a technique where required objects are provided to a class by the Spring Framework instead of the class creating them itself.

 

Basically, you don’t say “I will create the object”.
You say “Spring, please give me the object”.

 

Normal Way (Without DI)

Suppose we are making a project on Student Management System.

 

class StudentService {
    StudentRepository repo = new StudentRepository();
}

 

Here:

  • StudentService creates StudentRepository
  • Service is directly dependent on Repository
  • This is called tight coupling

 

Problem:

  • If repository logic changes → service class also affected
  • Hard to test
  • Not flexible

 

Many students write code like this in early days (even I did 😅).

 

Using Dependency Injection

Now see this:

 

class StudentService {
    StudentRepository repo;

    StudentService(StudentRepository repo){
        this.repo = repo;
    }
}

 

Here:

  • Service is not creating repository
  • Repository is given from outside
  • Loose coupling happens

 

And in Spring, the framework automatically creates and provides these objects.

So developer tension becomes less.

 

Real Life Example (College Style)

Think like this:

  • You need notes before exam.
  • You can either:
    • Write all notes yourself (hard work 😓)
    • Or take notes from your topper friend (smart work 😎)

 

Dependency Injection is like:

Instead of creating everything yourself you take what you need from someone who manages it properly.

 

Spring is that “topper friend”.

 

Why Do We Need Dependency Injection?

Many students get confused here. So let’s make it practical.

 

When project size increases:

  • More classes
  • More connections
  • More object creation
  • More confusion

 

Without DI:

  • Code becomes tightly connected
  • Hard to modify
  • Hard to test
  • Hard to scale

 

With DI:

  • Objects are managed by Spring container
  • Easy to replace components
  • Clean architecture
  • Better maintainability

 

Types of Dependency Injection

Spring provides mainly three types of Dependency Injection.

 

Constructor Injection

Dependencies are provided through constructor.

 

@Component
class StudentService {

    private StudentRepository repo;

    public StudentService(StudentRepository repo){
        this.repo = repo;
    }
}

 

Spring automatically calls constructor and injects object.

 

When to use:

  • When dependency is mandatory
  • For better immutability
  • Recommended by most developers

 

When I started Spring Boot, I ignored constructor injection. But later I realized it’s cleaner and safer.

 

Setter Injection

Dependencies are provided using setter methods.

 

@Component
class StudentService {

    private StudentRepository repo;

    @Autowired
    public void setRepo(StudentRepository repo){
        this.repo = repo;
    }
}

 

When to use:

  • When dependency is optional
  • When you may change dependency later

 

Field Injection

Dependencies are injected directly into fields.

 

@Component
class StudentService {

    @Autowired
    private StudentRepository repo;
}

 

This is easiest to write.

 

But many experienced developers don’t prefer it because:

  • Hard to test
  • Not good for large applications

 

Still, beginners use it a lot (I also used this in my first mini project 😅).

 

Comparison Table

Type How Injection Happens Best Use Case Recommended
Constructor Injection Through constructor Mandatory dependencies ✅ Yes
Setter Injection Through setter methods Optional dependencies 👍 Sometimes
Field Injection Directly on variables Quick and small projects ❌ Not preferred

 

@Autowired Annotation

Now comes the most famous annotation in Spring @Autowired

 

When I first saw it, I used it everywhere without understanding. Later I learned what it actually does.

 

What is @Autowired?

@Autowired tells Spring:

“Find the required object and inject it here automatically.”

 

Spring searches for matching bean and provides it.

 

Example:

@Component
class StudentService {

    @Autowired
    private StudentRepository repo;
}

 

Spring will:

  • Create StudentRepository object
  • Inject into StudentService automatically

 

No need to write new keyword.

 

Where Can We Use @Autowired?

You can use it in:

 

Constructor

@Autowired
public StudentService(StudentRepository repo){
    this.repo = repo;
}

 

Setter Method

@Autowired
public void setRepo(StudentRepository repo){
    this.repo = repo;
}

 

Field (most common for beginners)

@Autowired
private StudentRepository repo;

 

Important Point

From Spring 4.3+, if a class has only one constructor you don’t even need @Autowired.

 

Spring understands automatically.

Cleaner code. Less annotations.

 

How Spring DI Works Internally (Simple Version)

Don’t worry, no deep theory.

 

Just basic flow:

  1. Spring starts application
  2. Scans classes with annotations like:
    • @Component
    • @Service
    • @Repository
    • @Controller
  3. Creates objects (called Beans)
  4. Stores them in Spring Container
  5. When needed injects beans automatically

 

So container manages everything.

You just focus on logic.

 

Benefits of Dependency Injection

This is important for exams and interviews.

 

Loose Coupling

Classes don’t depend tightly on each other.

 

If repository changes:

  • Service doesn’t break

 

Very helpful in big projects.

 

Easy Testing

You can easily replace real objects with the mock objects.

 

For example:

  • Instead of real database
  • Use fake data for testing

 

This is very useful in unit testing.

 

Better Code Management

Spring manages object creation.

 

So:

  • Less boilerplate code
  • Cleaner structure
  • Better readability

 

Reusability

Same dependency can be used in multiple classes.

 

Like:

  • One EmailService
  • Used by StudentService, AdminService, PaymentService

 

Scalability

Large applications need clean architecture.

 

DI helps manage complexity easily.

 

Faster Development

You don’t needed to worry about:

  • Object creation
  • Lifecycle management

 

Spring handles it.

You focus on business logic.

 

Practical Example (Project Based)

Suppose you are building:

Employee Management System (very common project in B.Tech)

 

Layers:

  • Controller → Handles requests
  • Service → Business logic
  • Repository → Database operations

 

Without DI:

  • Each layer creates objects manually
  • Messy code

 

With DI:

  • Spring connects layers automatically
  • Smooth flow
  • Professional structure

 

When I made my first Spring Boot CRUD project DI made things much simpler. Initially I didn’t understand but once errors started coming, I realized why proper injection matters.

 

Common Mistakes Beginners Make

I made these mistakes, so sharing honestly.

  • Using new keyword even with Spring
  • Not using annotations properly
  • Field injection everywhere
  • Not understanding bean lifecycle

 

Best way to learn:

  • Build small projects
  • Break code
  • Fix errors
  • Repeat

 

FAQs

 

1. Is Dependency Injection only used in Spring?

No. DI is a design pattern. Spring just provides easy implementation.

2. Which injection type is best?

Constructor Injection is best. Most recommended in real projects.

3. What happens if multiple beans exist?

Spring gets confused. You must use:

  • @Qualifier
  • or @Primary
4. Is @Autowired mandatory?

No. If single constructor exists, Spring injects automatically.

5. Is DI important for freshers?

Yes, very important. Most companies using Spring expect this knowledge.

 

Conclusion

Dependency Injection may sound complex at first but honestly, it’s a very simple and powerful concept.

 

In simple words:

Don’t create objects yourself. Let Spring manage and provide them.

 

That’s it.

 

It makes your code:

  • Cleaner
  • Flexible
  • Easy to test
  • Easy to maintain

 

If you are preparing for exams, interviews or building Spring Boot projects, DI is a must know topic.

 

My suggestion:

  • Practice small examples
  • Use constructor injection
  • Avoid tight coupling
  • Build real projects

 

Once you use DI properly you will never want to go back to manual object creation.

 

Happy Coding 🚀

 

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !)#days=(20)

We use cookies to personalize content and ads, provide social media features, and analyze our traffic. By clicking "Accept", you consent to our use of cookies. Privacy Policy Cookies Policy
Accept !
Breaking News | News |