Spring Tutorial: Autowiring in Detail

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!

@Autowired

MathOperation mathOperation;

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.

@Autowired

@Qualifier(value = addOperation)

MathOperations mathOperations1;

So now a call to mathOperations1.performOperation(); will call the method defined in Add class.

Similarly,

@Autowired

@Qualifier(value = “multiplyOperation)

MathOperations mathOperations2;

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

@Autowired

MathOperations addOperation;

So a call  addOperation.performOperation(); will call the method defined in Add class.

Similarly,

@Autowired

MathOperations multiplyOperation;

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

@Autowired

DerivativeOperation derivativeOperation;

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.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s