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:
-
Choosing an implementation of ApplicationContext — for example,
ClassPathXmlApplicationContextfor XML configuration orAnnotationConfigApplicationContextfor annotation-based configuration. -
Loading the configuration — Spring reads bean definitions from XML files, classes with
@Configurationannotations, or other sources. -
Creating and initializing beans — Spring creates objects, manages their dependencies (via DI), and calls initialization methods.
-
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.