I used @Autowired everywhere in my Spring Boot code. 😬 Then a senior developer reviewed my code and said: "This is wrong. Use Constructor Injection." I had no idea why. Here's what I learned 👇 ━━━━━━━━━━━━━━━━━━━━━ ❌ @Autowired (Field Injection) — DON'T do this: @Autowired private UserService userService; Problems: → Hard to unit test → Hides dependencies → Can cause NullPointerException → Breaks SOLID principles ✅ Constructor Injection — DO this: private final UserService userService; public UserController(UserService userService) { this.userService = userService; } Benefits: → Easy to unit test → Dependencies are visible & clear → Works with final fields (immutable) → Circular dependency caught at startup ━━━━━━━━━━━━━━━━━━━━━ 🏆 Pro Tip: Use @RequiredArgsConstructor from Lombok It auto-generates the constructor for you! I share tips like these EVERY DAY in my newsletter "Spring Boot Engineering Digest" 📩 768+ Java developers are already reading it. Link in comments 👇 💬 Were YOU using @Autowired? Comment below! ♻️ Repost this to help a fellow Java developer! #SpringBoot #Java #BackendDevelopment #JavaDeveloper #CleanCode #SoftwareEngineering #Microservices #Programming #SpringFramework #100DaysOfCode
I learned this a few years ago, is incredible how we can make mistakes with practices that we thought as normal
Glad you found this useful! This is something I originally shared earlier—happy to see it resonating. Would appreciate a mention next time 😊
Totally relatable! 😄 Field injection (@Autowired) is quick, but constructor injection ensures better testability, immutability, and avoids hidden dependencies. A key lesson in Spring Boot development 👍