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:
-
Creating a configuration class or XML configuration — where beans and their dependencies are declared.
-
Initializing ApplicationContext — using the
AnnotationConfigApplicationContextclass for annotation-based configuration orClassPathXmlApplicationContextfor XML. -
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.