Sometimes we need to have multiple Beans of same type to be available at runtime so that we can use any of the Bean based on our need dynamically. But if you do not use @Qualifier then Spring will give you a Bean creation error because it faces ambiguity of resolving which bean to inject.
I will discuss how to resolve this dilemma in an easy and elegant way. You will be surprised to know that we can resolve such situation by applying Simple Factory Pattern in Spring
Scenario
Suppose we have 2 services to send SMS (ie: Twilio and SNS) (Not necessarily it has to be two. It can be any number). Some client use Twilio and some use SNS. We need to route user at runtime based on users’ preference.
Let’s jump into code then
The Code
Let’s have a contracts for SMS Service as follow
and the contracts for the service
Let’s implement SMS Services
and
Now let’s create the Factory for these services 🙂
Now we can use this in controller as follows
Caveats
In above example all Beans are created in eagerly manner during service or application boot. Lazy Bean initialization can be possible but that is another topic and deserve a full post of its own. 😉
Hope this helps!! Feel free to leave comments below. I am all ears!!