When I started with Spring, annotations like @Autowired felt like magic spells. But relying on "magic" doesn't work in production. To truly master the framework, we have to look under the hood.
Here is a breakdown of how the Inversion of Control (IoC) container actually works:
🔹 The Container: Many confuse BeanFactory with ApplicationContext.
BeanFactory is lazy (instantiates beans only when asked).
ApplicationContext (the Spring Boot default) is eager. It creates all Singletons at startup to catch configuration errors early.
🔹 Recipe vs. Meal: Spring doesn't just create objects; it creates BeanDefinitions first. Think of the Definition as the recipe and the actual Bean as the meal.
🔹 Dependency Injection: Stop using Field Injection (@Autowired on variables).
Constructor Injection is the industry standard. It ensures immutability, prevents NullPointerExceptions, and makes Unit Testing possible without loading the whole context.
🔹 The Circular Dependency Trick: How does Spring handle Bean A needing Bean B, which needs Bean A? It uses a clever Three-Level Cache system to expose "raw" bean factories before they are fully initialized.
Understanding these internals specifically the lifecycle from BeanDefinition to Singleton Cache is often what distinguishes a Junior developer from a Senior Engineer.
Top comments (0)