How to autowire an interface when there are several implementations of that interface?
Problem: Consider an example where we have an interface defined as Math Interface which is implemented by two classes Add and Multiply . Now, the question is how to autowire the two classes? Autowiring like below on interfaces implemented by several classes will fail!
Somewhere in the class there is a call mathOperation.performOperation(); Spring is in trouble now as it does not know which performOperation() it should call? the one in Add or the one in Multiply class? The error that it gives is as follows: ERROR: Trying to find a bean but found two!
There are two solutions for this problem
- Solution1: Use annotation qualifier specifying the instance of the class that will allow spring to identify which particular class to be invoked.
@Qualifier(value = “addOperation“)
So now a call to mathOperations1.performOperation(); will call the method defined in Add class.
@Qualifier(value = “multiplyOperation“)
So now a call to mathOperations2.performOperation(); will call the method defined in Multiply class.
- Solution2: Use the name of that specific implemented class object when auto wiring instead of using generic interface instance name. For example
So a call addOperation.performOperation(); will call the method defined in Add class.
So a call multiplyOperation.performOperation(); will call the method defined in Multiply class.
How to autowire an interface when there is only one implementation of that interface.
Imagine there exists this interface called ComplexMathOperation defined here: ComplexMathOperationInterface and the only implementation of this interface called DerivativeOperation defined here: DerivativeOperationClass . How to autowire in this scenario?
There are two simple ways to autowire:
- Using the interface name@AutowiredComplexMathOperation complexMathOperation;
With this a call to performComplexMathOperations() will have no issues.
- Using the class name
With this a call to performComplexMathOperations() will also have no issues but this defeats the purpose of using interface for auto wiring as it directly uses the class name.