DEV Community

Cover image for Spring @Autowired tricks
Sameh Muhammed
Sameh Muhammed

Posted on • Edited on

1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs