Spring @Autowired tricks

smuhammed

Sameh Muhammed

Posted on October 10, 2022

Spring @Autowired tricks

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.

Image description

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.

Image description

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.

Image description

Image description

Or in a different way you can use Map to fire specific logic based in some parameter value like below image.

Image description

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.

Image description

  • we made our examples with field injection and @Autowired but it works as well with constructor injection like below and this is recommended.

Image description

IF YOU LIKED THE POST, THEN YOU CAN BUY ME A COFFEE, THANKS IN ADVANCE.

Buy Me A Coffee

💖 💪 🙅 🚩
smuhammed
Sameh Muhammed

Posted on October 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Spring @Autowired tricks
spring Spring @Autowired tricks

October 10, 2022