Sobes.tech
Junior — Middle

How is the application context created and initialized in Spring Framework?

sobes.tech AI

Answer from AI

In the Spring Framework, the application context is created using an implementation of the ApplicationContext interface. This usually happens when the application starts, as Spring loads the configuration and initializes all beans.

The process of creating and initializing the context:

  1. Choosing an implementation of ApplicationContext — for example, ClassPathXmlApplicationContext for XML configuration or AnnotationConfigApplicationContext for annotation-based configuration.

  2. Loading the configuration — Spring reads bean definitions from XML files, classes with @Configuration annotations, or other sources.

  3. Creating and initializing beans — Spring creates objects, manages their dependencies (via DI), and calls initialization methods.

  4. Ready for use — after full initialization, the context is ready to provide beans on demand.

Example of creating a context with annotations:

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MyBean bean = context.getBean(MyBean.class);
        bean.doSomething();
    }
}

Here, AppConfig is a class with @Configuration annotations and bean definitions, and AnnotationConfigApplicationContext loads and initializes the context based on it.