Video in progress

Junior 🌱 Spring

What is the ApplicationContext and what does it do when the application starts?

The ApplicationContext is Spring's IoC container: it creates beans, holds them and wires them, and also gives access to configuration, events and resources.

📖 Answer

When the application starts, the ApplicationContext comes up first. In order, it:

  1. reads the configuration (@Configuration, component scan, auto-config);
  2. builds the list of beans;
  3. creates them and puts dependencies in place;
  4. calls the @PostConstruct methods;
  5. closes the beans when the application stops.

In Spring Boot, the context is returned by SpringApplication.run(...):

ConfigurableApplicationContext ctx = SpringApplication.run(App.class, args);
OrderService s = ctx.getBean(OrderService.class);

In normal code you almost never write getBean — you get the dependency injected.

The difference from BeanFactory: BeanFactory is the simplest container. ApplicationContext adds events, i18n, Environment, resource loading and so on on top of it. In practice you always work with ApplicationContext.