I have been using dependency injection using @Autowired
in Spring boot. From all the articles that I have read about dependency injection, they mention that dependency injection is very useful when we (if) decide to change the implementing class in the future.
For example, let us deal with a Car
class and a Wheel
interface. The Car
class requires an implementation of the Wheel
interface for it to work. So, we go ahead and use dependency injection in this scenario
// Wheel interface
public interface Wheel{
public int wheelCount();
public void wheelName();
...
}
// Wheel interface implementation
public class MRF impements Wheel{
@Override
public int wheelCount(){
......
}...
}
// Car class
public class Car {
@Autowired
Wheel wheel;
}
Now in the above scenario, ApplicationContext
will figure out that there is an implementation of the Wheel interface and thus bind it to the Car class. In the future, if we change the implementation to say, XYZWheel
implementing class and remove the MRF
implementation, then the same should work.
However, if we decide to keep both the implementations of Wheel
interface in our application, then we will need to specifically mention the dependency we are interested in while Autowiring it. So, the changes would be as follows -
// Wheel interface
public interface Wheel{
public int wheelCount();
public void wheelName();
...
}
@Qualifier("MRF")
// Wheel interface implementation
public class MRF impements Wheel{
@Override
public int wheelCount(){
......
}...
}
// Wheel interface implementation
@Qualifier("XYZWheel")
public class XYZWheel impements Wheel{
@Override
public int wheelCount(){
......
}...
}
// Car class
public class Car {
@Autowired
@Qualifier("XYZWheel")
Wheel wheel;
}
So, now I have to manually define the specific implementation that I want to Autowire. So, how does dependency injection help here ? I can very well use the new
operator to actually instantiate the implementing class that I need instead of relying on Spring to autowire it for me.
So my question is, what are the benefit of autowiring/dependency injection when I have multiple implementing classes and thus I need to manually specify the type I am interested in ?