Sobes.tech
Junior — Middle

How is the Spring context configured and launched in an application?

sobes.tech AI

Answer from AI

Setting up and launching the Spring context in a Java application typically involves the following steps:

  1. Creating a configuration class or XML configuration — where beans and their dependencies are declared.

  2. Initializing ApplicationContext — using the AnnotationConfigApplicationContext class for annotation-based configuration or ClassPathXmlApplicationContext for XML.

  3. Retrieving beans from the context — for further use in the application.

Example using annotations:

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

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MyService service = context.getBean(MyService.class);
        service.performAction();
    }
}

Thus, the Spring context is created and started, managing the lifecycle of beans and their dependencies.