Spring Dependency Injection Methods

Spring Dependency Injection Methods, Their Advantages & Disadvantages

Photo by Diana Polekhina on Unsplash

Field Injection

Spring assigns the required dependencies directly to the fields on annotating with @Autowired annotation. Field Injection uses reflection to set the values of private variables.

Field Injection Example — https://dzone.com/articles/spring-di-patterns-the-good-the-bad-and-the-ugly

Constructor Injection

The dependencies required for the class are provided as arguments to the constructor. Annotation of constructors (@Inject or @Autowired) for dependency injection has been optional since Spring Framework version 4.2.

Constructor Injection Example — https://dzone.com/articles/spring-di-patterns-the-good-the-bad-and-the-ugly

Setter Injection

We provide the required dependencies as field parameters to the class and the values are set using the setter methods of the properties. We have to annotate the setter method with the @Autowired annotation.

Setter Injection Example — https://dzone.com/articles/spring-di-patterns-the-good-the-bad-and-the-ugly

Constructor Injection Using Project Lombok 🌶

Constructor Injection with Project Lombok — https://springframework.guru/best-practices-for-dependency-injection-with-spring/

Happy Coding!

--

--

I would love to change the world, but they won’t give me the source code | coding 👩🏼‍💻 | coffee ☕️ | jazz 🎷 | anime 🐲 | books 📚 | drawing 🎨

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nil Seri

I would love to change the world, but they won’t give me the source code | coding 👩🏼‍💻 | coffee ☕️ | jazz 🎷 | anime 🐲 | books 📚 | drawing 🎨