Sub topic 4
The ApplicationContext as the container
This chapter assumes you know what a bean is and why Spring creates objects for you, as covered in the earlier chapters. You should be comfortable reading Java configuration classes and have spring-context on your classpath. With Maven that means the org.springframework:spring-context dependency. Spring Boot projects already include it.
What the container is
Your classes never create their collaborators. Something else has to, and in Spring that something is the container. The container reads descriptions of your beans, creates the objects, injects dependencies, and hands the finished objects back. It also destroys them when the application stops.
In code, the container is an object that implements org.springframework.context.ApplicationContext. Every bean you inject was created by one.
The root interface is BeanFactory. It provides the basics: define beans, create them, look them up. ApplicationContext extends it and adds the features that applications need:
| Capability | What it gives you |
|---|---|
| Eager singleton creation | Singleton beans are built at startup, so wiring errors appear immediately. |
| Annotation and Java config processing | `@Configuration`, `@Bean`, `@Component` scanning and `@Autowired` all work. |
| Event publishing | Beans can publish and listen to events, such as context refresh and close. |
| `Environment` | Profiles and properties are available to the container. |
| Message and resource loading | Internationalized messages and `classpath:` or `file:` resources. |
In application code, use ApplicationContext. Use a bare BeanFactory only in unusual, memory-constrained cases.
Common implementations
You rarely pick an implementation in a Spring Boot application, but you should recognize them.
| Class | Typical use |
|---|---|
| `AnnotationConfigApplicationContext` | Standalone applications and tests, built from `@Configuration` classes or a package to scan. |
| `ClassPathXmlApplicationContext` | Legacy applications configured with XML files. |
| `AnnotationConfigServletWebServerApplicationContext` | What `SpringApplication.run` creates for a Spring Boot web application. |
| `GenericApplicationContext` | A flexible base class, often used in tests and for programmatic registration. |
All of them follow the same lifecycle, described next.
What happens during refresh
Creating a context from configuration classes calls refresh() for you. This is the step that turns descriptions into live objects.
- Bean definitions are registered. A bean definition is a recipe: the class, the scope, the dependencies, and the init and destroy methods. At this stage no bean objects exist yet.
- Factory post-processors run. A
BeanFactoryPostProcessorcan change definitions before any bean is built. This is how@Configurationclasses and component scanning are processed, and how${...}placeholders are resolved. - Bean post-processors are registered. A
BeanPostProcessorruns around each bean's initialization. Processing of@Autowired,@PostConstructand proxy creation (for features such as transactions) all happen here. - Singletons are instantiated. The container creates every non-lazy singleton bean, resolving dependencies in the order they require.
- The refreshed event is published. Listeners learn that the context is fully started.
Because step 4 is eager, a missing or ambiguous dependency stops the application during startup. It does not fail later, when a user first triggers the code path.
A tour of a running context
This program builds a context, uses it, inspects it, and closes it. It listens to the two lifecycle events so you can see where they occur.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
public class ContextTour {
interface MessageSender {
void send(String to, String body);
}
static class NotificationService {
private final MessageSender sender;
NotificationService(MessageSender sender) {
this.sender = sender;
}
void welcome(String user) {
sender.send(user, "Welcome!");
}
}
static class LifecycleLogger {
@EventListener
void onRefresh(ContextRefreshedEvent event) {
System.out.println("context refreshed");
}
@EventListener
void onClose(ContextClosedEvent event) {
System.out.println("context closing");
}
}
@Configuration
static class AppConfig {
@Bean
MessageSender emailSender() {
return (to, body) -> System.out.println("email to " + to + ": " + body);
}
@Bean
NotificationService notificationService(MessageSender sender) {
return new NotificationService(sender);
}
@Bean
LifecycleLogger lifecycleLogger() {
return new LifecycleLogger();
}
}
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
NotificationService byType = ctx.getBean(NotificationService.class);
NotificationService byName =
ctx.getBean("notificationService", NotificationService.class);
byType.welcome("ana");
System.out.println("senders: "
+ java.util.Arrays.toString(ctx.getBeanNamesForType(MessageSender.class)));
System.out.println("same instance: " + (byType == byName));
}
}
}The program prints the lines below. Spring's own log lines may also appear, depending on your logging setup.
context refreshed
email to ana: Welcome!
senders: [emailSender]
same instance: true
context closingThree things are worth noticing:
context refreshedappears before any code inmainuses the context. The constructor call performed the whole refresh.- Both lookups return the same object. The default scope is singleton, so there is one instance per bean definition in a given context.
context closingappears when thetryblock ends.AnnotationConfigApplicationContextimplementsAutoCloseable, and closing it publishes the event, then destroys the singletons.
Looking beans up
The container offers several lookup methods:
getBean(Class<T>)finds a bean by type.getBean(String)finds it by name and returnsObject.getBean(String, Class<T>)finds it by name and checks the type.getBeansOfType(Class<T>)returns a map of bean name to bean for every match.getBeanNamesForType(Class<?>)returns names without creating the beans.containsBean(String)checks whether a bean with that name exists.
Lookup fails with a specific exception, and the type tells you what went wrong:
| Exception | Cause |
|---|---|
| `NoSuchBeanDefinitionException` | Nothing matches the requested type or name. |
| `NoUniqueBeanDefinitionException` | Several beans match and none is marked `@Primary`. |
| `BeanCreationException` | A matching bean exists but threw an error while it was being built. |
If you need a bean that may be absent, or one created on demand, inject an ObjectProvider<T> instead of the whole context. Its getIfAvailable() method returns null when there is no bean. Its getObject() method asks the container each time you call it, which suits prototype beans.
Eager and lazy creation
Singletons are created at refresh by default. Two consequences follow:
- Startup time grows with the number of singletons and with any slow work in their constructors or
@PostConstructmethods. - Errors surface early, which is usually what you want.
Annotating a bean with @Lazy defers creation until something first asks for it. This helps when a bean is expensive and rarely used. The cost is that a wiring problem in that bean can first appear at runtime, in the middle of a request.
Closing the context
Closing a context stops the application's Spring side. It publishes ContextClosedEvent, then calls destruction callbacks on singleton beans (@PreDestroy, DisposableBean, and destroy methods). Prototype beans are not destroyed by the container, because it no longer holds a reference to them.
Where you close depends on how you started:
- With try-with-resources, as in the example above, the end of the block closes the context.
- In a long-running program, call
ctx.registerShutdownHook()once after creating the context. The JVM then closes it on exit, including on Ctrl+C. - Spring Boot registers the shutdown hook for you.
A closed context cannot be refreshed again. Calling getBean on it throws IllegalStateException.
Parent and child contexts
A context can have a parent. A child sees its parent's beans, but the parent cannot see the child's. Lookups and injection search the child first, then the parent.
Classic Spring MVC applications used this arrangement, with a root context for services and a child context for web components. You will meet it mostly in older codebases and in some test setups. Spring Boot normally uses a single context. A common mistake in parent-child setups is declaring the same bean in both contexts, which creates two separate instances.
Where the context itself can be injected
The context is a bean-like object that you can inject. A bean can declare an ApplicationContext constructor parameter, and Spring supplies the running context. The same works for Environment, BeanFactory, and ApplicationEventPublisher. Prefer the narrowest type. A class that only publishes events needs ApplicationEventPublisher, not the whole context.
Exercise
In the tour program, you remove the @Bean method for emailSender but leave the others unchanged. When and how does the failure appear, and which exception is at the root of it?
Show answer
The failure appears while the context is being created, during singleton instantiation in refresh, before main calls anything on the context. Spring cannot supply the MessageSender parameter of notificationService, so it throws a BeanCreationException whose root cause is a NoSuchBeanDefinitionException for MessageSender.
Exercise
A teammate adds a second MessageSender bean named smsSender to the tour program, with no @Primary. What happens at startup, and does ctx.getBeanNamesForType(MessageSender.class) still work?
Show answer
Startup fails, because the notificationService method has one MessageSender parameter and two beans match. The cause is a NoUniqueBeanDefinitionException, wrapped in a BeanCreationException. The parameter name sender does not match either bean name, so Spring has no fallback. getBeanNamesForType would work if the context started, and it would return both names, because it only lists matches and does not need a single winner.