🔍 How Dependency Injection (DI) Works Internally in Spring Boot When I first used @Autowired, I wondered… 👉 How does Spring automatically create and inject objects? Here’s what I learned: 1️⃣ When the application starts, Spring creates an Application Context (IoC Container). 2️⃣ It scans for classes annotated with: @Component, @Service, @Repository, @Controller 3️⃣ Spring creates objects (beans) of these classes and stores them inside the container. 4️⃣ When a class needs a dependency (using @Autowired), Spring: ✔ Finds the required bean ✔ Injects it automatically So instead of: UserService service = new UserService(); Spring manages object creation for us. 💡 This is called Inversion of Control (IoC). Result: ✔ Loose coupling ✔ Better testability ✔ Cleaner architecture Understanding internals > Just memorizing annotations 🚀 #SpringBoot #DependencyInjection #Java #BackendDeveloper #Learning
Nice explanation of the internals. One important nuance worth mentioning is that constructor injection is now the recommended approach over field injection with @Autowired. The reason is that with constructor injection your dependencies are explicit, the object can't be created in an invalid state, and it makes unit testing way easier because you can just pass mock objects directly without needing a Spring context or reflection hacks. Also Spring actually does constructor injection automatically if you have a single constructor, so you don't even need the @Autowired annotation at all in that case. Another thing to explore is how Spring handles circular dependencies, that's where the three level cache in the bean creation process gets really interesting.
Yes Internally Spring stores beans inside the IoC container (ApplicationContext). Under the hood, it uses Map-based caches like beanDefinitionMap and singletonObjects (bean name → instance). So technically, beans are managed and stored in Maps inside the BeanFactory implementation for fast lookup at runtime.