Dependency Injection with Spring Boot

ByDasun De Silva

Jul 3, 2021

This article will explain how Sprint Boot framework achieve IoC , inverstion of control via DI , dependency injection.

However pickocode has explained how traditional Java program work with and without DI. If you want to watch that follow below URL.

Dependency Injection

Subscribe our YouTube channel for more tutorial with programming examples.

In traditional programming what we are doing is we create an interface and an implemented class. Then out side class will invoke that implemented class (s) with new keyword and working with rest of the things.  You can go to this article if want to know how traditional Java achieved IoC principal using DI design pattern. 

Now lets get back to the topic , how spring boot achieve DI .

Spring boot DI can be achieved using following ways. 

  • Constructor DI
  • Setters DI
  • Fields DI

Constructor Dependency Injection

From the constructor we can invoke dependencies what we need. Check below example how to achieve constructor dependency. You may heard about Beans annotation and Configuration annotation in sprint. Where @Configuration tells that this class is for defining beans. Where @bean annotation defines a bean. Moreover when we create a bean it act as a singleton object, only one object per project. 

public class CarConfig{

    public Engine v6Engine() {
        return new V6EngineImpl();

    public Car cefiro() {
        return new Car(v6Engine());

Setter Dependency Injection

Container can link the perticular bean from setter methods

public Car cefiro() {
    Car cefiroCar = new Car ();
    return cefiroCar ;

Field based Dependency Injection

Simply we can link and invode a bean from a property

public class Car{
    private Engine v6Engine; 

Leave a Reply