Sub topic 4
The ApplicationContext as the container
This chapter assumes you know what a bean is and how dependency injection works. It also assumes you can read Java annotations and a basic @Configuration class. Here you will see the object that does the work: the ApplicationContext.
What the container does
The ApplicationContext is Spring's inversion of control container. It reads bean definitions, creates the beans, injects their dependencies, and runs their lifecycle callbacks. It also keeps the finished beans so you can look them up later.
ApplicationContext builds on a simpler interface, BeanFactory, which provides the core creation and lookup. The context adds features you normally want:
- An
Environmentfor profiles and properties. - Event publishing.
- Resource loading.
- Message lookup for internationalization.
In application code you almost always work with an ApplicationContext, not a bare BeanFactory.
What happens at startup
When you create a context, it processes its configuration in a fixed order. Singleton beans are created eagerly, so the context is fully built before your code gets a reference to it.
Because singletons are built eagerly, a missing or ambiguous dependency fails at startup with an exception, not later when a user triggers the code path. This is usually what you want.
Creating and using a context
AnnotationConfigApplicationContext builds a context from Java configuration classes or from component scanning. This example uses MessageSender, NotificationService and AppConfig from earlier chapters.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
NotificationService service = ctx.getBean(NotificationService.class);
service.welcome("ana");
}
}
}The constructor argument is the configuration class. The context registers its @Bean methods, creates emailSender first, then passes it to notificationService. The try block calls close() when it ends, which destroys the singletons.
Common context types
| Type | Built from | Typical use |
|---|---|---|
| `AnnotationConfigApplicationContext` | `@Configuration` classes or scanned packages | Plain Java applications and tests |
| `ClassPathXmlApplicationContext` | XML files on the classpath | Older applications |
| `ConfigurableApplicationContext` | Returned by `SpringApplication.run` | Spring Boot applications |
You rarely create the Boot context yourself. SpringApplication.run(...) builds and returns it.
Looking up beans
getBean has several forms:
getBean(NotificationService.class)looks up by type.getBean("emailSender")looks up by name and returnsObject.getBean("emailSender", MessageSender.class)looks up by name and checks the type.
Two exceptions are common. NoSuchBeanDefinitionException means nothing matches. NoUniqueBeanDefinitionException means more than one bean matches the type and nothing selects one.
Common mistakes
- Not closing the context. Destroy callbacks such as
@PreDestroynever run. Use try-with-resources, or let Spring Boot manage it. - Creating several contexts. Each context has its own singletons. Two contexts built from the same class give you two separate
NotificationServiceinstances. - Expecting lazy failures. A wiring problem in a singleton stops startup, even if no code uses that bean yet.
Exercise
A program creates two AnnotationConfigApplicationContext objects from the same AppConfig class and calls getBean(NotificationService.class) on each. Are the two results the same object? Also, when does Spring detect that AppConfig has no MessageSender bean, and what exception is thrown?
Show answer
They are different objects. Singleton scope means one instance per context, not one per JVM. Spring detects the missing bean while creating the context, before any getBean call, because singletons are created eagerly. It fails with an exception caused by NoSuchBeanDefinitionException, wrapped in an UnsatisfiedDependencyException.