The IoC Container and ApplicationContext
The IoC Container and ApplicationContext
The IoC container is the machinery that instantiates, configures, and assembles your beans and manages their full lifecycle. In modern Spring you rarely interact with it directly, but understanding what it does explains why so much Spring code appears to work magically.
What the container does
On startup the container reads your configuration, creates bean definitions, instantiates the beans, resolves dependencies between them, and wires them together. It also applies post-processing: proxies for AOP or transaction management, environment binding, and lifecycle callbacks.
ApplicationContext
ApplicationContext is the interface you hold when you need the container programmatically. It extends bean management with internationalization, event publication, resource loading, and environment abstractions. In a Boot application, the context is created by SpringApplication.run and is cached as a singleton bean.
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
GreetingService service = context.getBean(GreetingService.class);
System.out.println(service.greet());
context.close();
Bean factory vs application context
The older BeanFactory is the bare container; ApplicationContext adds enterprise features on top. Nearly all applications use an ApplicationContext. You typically obtain beans by type or name, but prefer constructor injection and let the container do that work for you.
Lifecycle in mind
Knowing the container helps you reason about behavior: singletons are created eagerly by default, dependencies are resolved at startup, and a bean's lifecycle callbacks run in a predictable order. Errors surface early, at context creation, rather than later at runtime.
Key Points
- The IoC container creates and wires beans from configuration.
ApplicationContextis the main container interface in modern Spring.- Boot builds the context for you with
SpringApplication.run. - Beans are resolved and wired at startup, so misconfiguration fails fast.
- Prefer letting the container inject, not hunting beans manually.