Sobes.tech
Junior — Middle

When during the initialization process of the Spring container is the context object created, and when are the beans created?

sobes.tech AI

Answer from AI

The Spring container is created during the initialization of the ApplicationContext (for example, ClassPathXmlApplicationContext or AnnotationConfigApplicationContext). The context object is created immediately when the application starts or when the context constructor is called.

Bean creation occurs during the context initialization process. By default, Spring creates all singleton beans immediately upon context initialization (eager initialization). This means that after the context is created, all singleton beans are already created and ready to use.

If a bean is declared with a prototype scope, it is created only upon the first request from the context.

Thus:

  • The context is created during ApplicationContext initialization.
  • Singleton beans are created immediately after the context is created.
  • Prototype beans are created on demand.

Example of context initialization with bean creation:

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyBean myBean = context.getBean(MyBean.class); // singleton already created

If lazy initialization is used, beans are created upon their first access, not at the start of the context.