Dependency Injection Example in Spring

November 6, 2020

I have got Circle and Rectangle classes with Shape interface implementation

Circle Class

package com.kayak.first;
public class Circle implements Shape {
    @Override
    public String calculateArea() {
        return "Circle Area";
    }
}

Raectangle Class


package com.kayak.first;
public class Reactangle implements Shape {
    @Override
    public String calculateArea() {
        return "Ractangle Area";
    }
}

Shape Interface

package com.kayak.first;
public interface Shape {
    public String calculateArea();
}

Now I have create the AreaService class to calculate the area of the each shape. I am passing the instance of the Shape to constructor and call the calculateArea method of the Shape

package com.kayak.first;
public class AreaService {

    private  Shape shape;

    AreaService(Shape shape){
        super();
        this.shape =shape;
    }

    public String getArea(){
        return this.shape.calculateArea();
    }

}

Inside the main method you can have the following code to test this

 AreaService areaService = new AreaService( new Reactangle());
 System.out.println(areaService.getArea());

AreaService class has the dependency classes Reactangle and Circle

How to implement with Spring

Now we will see how to implement the above dependency injection with Spring.

Shape interface

package com.kayak.first;
import org.springframework.stereotype.Component;
@Component
public interface Shape {
    public String calculateArea();
}

I have introduced @component annotation here.

Your Circle class

package com.kayak.first;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Component
@Primary
public class Circle implements Shape {
    @Override
    public String calculateArea() {
        return "Circle Area";
    }
}

@component and @Primary annotation are in this class

Next, your Rectangle class