Spring Framework
Dependency Injection: Why `new` Is Not Always Your Friend
Early in my career, I used the `new` keyword everywhere. `new UserService(new UserRepository(new Database()))`. I thought I was being efficient. Then came the day we needed to switch from MySQL to MongoDB. I had to go through every file that instantiated `UserRepository` and change the constructor. It was a nightmare. Dependency Injection (DI) solves this by inverting the control. Instead of the class creating its dependencies, they are provided (injected) from the outside. Using Spring’s IoC container, I now just annotate with `@Autowired` and let the framework manage the lifecycle. It makes the code decoupled, testable (because I can inject mocks), and flexible. If you’re starting with Java, learn Spring just for this principle alone. It enforces good architecture by making you think about how components connect.
2,945
Views
131
Words
1 min read
Read Time
May 2025
Published