Spring @Autowired tricks
Sameh Muhammed
Posted on October 10, 2022
Introduction
As we know Spring framework is a dependency injection framework that keep tracks from your classes and whenever you want an instance spring will provide that for you.
By Annotating your classes with @Service or @Component Spring at runtime will create instances from these classes and wherever you want an object from them you just use @Autowired so that spring knows that you need an object here.
Some Magic
But there is some tricks may add value to your code or make code cleaner , as image below we have IMove interface with 2 different implementations for it.
you can use @Autowired with List of IMove and spring will get all interface implementations and put them into the list , or you can use Map of String and IMove and spring will construct a map with service name as a key and an object of this service as a value like below image.
You can benefit from this for an example if you have a multiple validation logic over some value you can use @Autowired with List trick to group validators based on type and fire them in a much clean way like below images.
Or in a different way you can use Map to fire specific logic based in some parameter value like below image.
Notes
- just be careful when you have this setup and try in inject one object from the interface , application will not run because Spring will be confused as it will not know which implementation have to use to fulfill this injection , you can solve this situation with @primary or @Qualifier like this.
- we made our examples with field injection and @Autowired but it works as well with constructor injection like below and this is recommended.
IF YOU LIKED THE POST, THEN YOU CAN BUY ME A COFFEE, THANKS IN ADVANCE.
Posted on October 10, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.