Sobes.tech
Junior — Middle

How is the setup and configuration of the context carried out in applications using Spring?

sobes.tech AI

Answer from AI

In Spring applications, the application context (ApplicationContext) is responsible for creating and managing the lifecycle of beans, as well as for dependency configuration.

The setup and configuration of the context usually proceed as follows:

  1. Choosing the type of context:

    • ClassPathXmlApplicationContext — for configuration from XML files in the classpath.
    • AnnotationConfigApplicationContext — for configuration via Java classes with annotations.
    • GenericWebApplicationContext and others — for web applications.
  2. Initializing the context:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// or
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
  1. Configuring beans:

    • In XML via <bean>
    • In Java via @Configuration and @Bean
    • Using annotations @Component, @Service, @Repository with component scanning enabled (@ComponentScan)
  2. Retrieving beans from the context:

MyService service = context.getBean(MyService.class);
  1. Closing the context (if needed):
if (context instanceof ConfigurableApplicationContext) {
    ((ConfigurableApplicationContext) context).close();
}

Thus, setting up the context boils down to choosing a configuration method, describing beans and their dependencies, then initializing and using the context in the application.

How is the setup and configuration of the context… - sobes.tech