Spring boot @Autowired vs Dynamic Polymorphism in case of loose coupling?

505 Views Asked by At

Hi I guess this question is quite basic but please help out!!!

Let say I have one interface Write and 2 implementing classes Pen and Pencil

public interface Write {
    
    public void writeSomething();
}

public class Pen implements Write {

    @Override
    public void writeSomething() {
        System.out.println("Writing using Pen!!");
    }
}

public class Pencil implements Write {

    @Override
    public void writeSomething() {
        System.out.println("Writing using Pencil!!");
    } 
    
}

public class Test1 {
    
    public static void main(String[] args) {
        
        Write wr = new Pen();
        wr.writeSomething();
    }
}

public class Test2 {

    @Autowired
    @Qualifier("Pen")
    private static Write wr;

    public static void main(String[] args) {

        wr.writeSomething();
    }
}

Now,
How does Test2 class implementation of spring boot is better then Test1 class implementaion, in terms of loose coupling in java.

And what is the benefit of @Autowired then ?

2

There are 2 best solutions below

0
On

The @Autowired annotation create a single Object(Bean) that your application reused instead of creating new Object each time.

0
On

This is the fifth principle of SOLID - Dependency inversion. You need use interfaces, and don't use implementations.

One of advantages is when you create Test2 you can manage which implementation you will use. For example you can create both new Test2(Pen) or new Test2(Pencil) dependent on your requirements.Spring will create Test2 with any Writer implementation. But with Test1 you can't manage Writer implementation.

Also it gives possibility to easy test Test2 with Writer mocks.

@Autowired will inject Writer bean into Test2 bean. You have to add @Component or @Service annotation above Test2 class or create Test2 bean configuration in class with @Configuration.