ApplicationContext
ApplicationContext — the central point of Spring
In Spring, the container role is usually performed by ApplicationContext.
It keeps information about application objects, creates them, wires dependencies,
and provides access to already assembled instances.
The context is created when the application starts. After that, most code works not with the container itself, but with the objects it has prepared.
@Configuration
class AppConfig {
@Bean
GreetingService greetingService() {
return new GreetingService();
}
}
public class Main {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
var service = context.getBean(GreetingService.class);
service.greet();
}
}
}
In the example, AnnotationConfigApplicationContext creates a context from Java configuration.
Calling getBean() does not manually create some new object — we ask the container
to give us an instance that it manages.
What else the context can do
ApplicationContext is responsible for more than storing objects.
Through it, Spring also provides infrastructure for events, resources, messages,
and other framework features. But its main role for us right now is to be the place
where the application's graph of connected objects lives.
getBean() into the normal way to obtain dependencies.
In application code, dependencies are usually supplied by the container itself through DI.
Explicit access to the context is useful for understanding the mechanics and for some infrastructure tasks.