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:
-
Choosing the type of context:
ClassPathXmlApplicationContext— for configuration from XML files in the classpath.AnnotationConfigApplicationContext— for configuration via Java classes with annotations.GenericWebApplicationContextand others — for web applications.
-
Initializing the context:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// or
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
-
Configuring beans:
- In XML via
<bean> - In Java via
@Configurationand@Bean - Using annotations
@Component,@Service,@Repositorywith component scanning enabled (@ComponentScan)
- In XML via
-
Retrieving beans from the context:
MyService service = context.getBean(MyService.class);
- 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.