Spring injects dependencies in constructor without @Autowired annotation
🌸 How does Spring Inject Dependencies in a Constructor without @Autowired Annotation? 🌸
If you've stumbled upon code where Spring injects dependencies in a constructor without the @Autowired annotation, you might be scratching your head in confusion. Fear not, for we are here to shed light on this puzzling matter and provide you with easy solutions.
1️⃣ The Mysterious Constructor Injection In the code you mentioned, specifically in the AppRunner.java class, you might have noticed that the GitHubLookupService dependency is magically provided by Spring in the constructor of the class. But wait, there's no @Autowired annotation! 🧐
It turns out that Spring Boot has an automatic assumption when it comes to dependency injection in constructors. If a private field and a constructor argument match, Spring takes the hint and looks for a suitable bean to inject. In simple terms, it sees the constructor parameter and thinks, "Hey, I should find a bean that matches this type." 👀
This nifty feature is part of the Spring Framework, not just Spring Boot. So, whether you're using Spring or Spring Boot, you can enjoy this automatic dependency injection goodness. Pretty cool, right? 😎
2️⃣ The Case of the Missing Default Constructor But hold on, you might recall that providing a default constructor was mandatory for beans or services. So how come the AppRunner class doesn't have a default constructor? And how does Spring know which constructor to run if there are multiple options?
In this scenario, since there's only one constructor available, Spring knows to use it. If there were multiple constructors, you would need to explicitly indicate the one to use with the @Autowired annotation. But when there's only one, Spring happily assumes it should use that one. This saves you from having to clutter your code with unnecessary default constructors. 🙌
✨ Quick Recap:
Spring automatically injects dependencies in constructors without the @Autowired annotation.
This feature is present in both Spring and Spring Boot.
Spring matches the constructor parameter with a suitable bean based on field type.
When there's only one constructor available, Spring uses it without the need for a default constructor.
Now that you understand this hidden Spring magic, go forth and conquer your dependency injection challenges with confidence! If you encounter more questions or have other topics you'd like us to cover, feel free to reach out and join the discussion. Let's learn and grow together! 🚀✨
Got more questions about Spring? Comment below! 👇🤔