Spring面试题, Spring 中的 ApplicationContext 是什么?
Spring面试题, Spring 中的 ApplicationContext 是什么?
QA
Step 1
Q:: Spring 中的 ApplicationContext 是什么?
A:: Spring 中的 ApplicationContext 是一个接口,用于提供应用配置的上下文信息。它继承自 BeanFactory,并增加了一些企业级功能,如事件发布、国际化、以及应用生命周期管理。ApplicationContext 是 Spring 框架的核心,它管理着应用中的所有 Bean,并负责 Bean 的初始化、配置和管理。
Step 2
Q:: ApplicationContext 和 BeanFactory 有什么区别?
A:: ApplicationContext 和 BeanFactory 都是用于管理 Spring Bean 的容器,但 ApplicationContext 继承自 BeanFactory,并提供了更多高级功能。BeanFactory 主要用于简单的依赖注入,而 ApplicationContext 增加了国际化支持、事件传播、对特定上下文的访问以及应用层别的资源(如文件)的加载功能。
Step 3
Q:: 如何在 Spring 中获取 ApplicationContext?
A:: 在 Spring 中,可以通过实现 ApplicationContextAware 接口来获取 ApplicationContext 实例。这个接口有一个 setApplicationContext(ApplicationContext context)
方法,当 Bean 被创建并配置时,Spring 会调用这个方法并注入 ApplicationContext 实例。
Step 4
Q:: Spring 中有哪些类型的 ApplicationContext?
A:: Spring 中有几种常见的 ApplicationContext 实现,包括:
1.
ClassPathXmlApplicationContext:从类路径下的 XML 配置文件加载上下文。
2.
FileSystemXmlApplicationContext:从文件系统中的 XML 配置文件加载上下文。
3.
AnnotationConfigApplicationContext:从一个或多个基于注解的配置类中加载上下文。
Step 5
Q:: Spring 中的 Bean 是如何被管理的?
A:: 在 Spring 中,Bean 是由容器管理的。在 XML 配置文件或注解中定义 Bean 后,Spring 容器会在应用启动时初始化这些 Bean,并负责它们的生命周期管理,包括依赖注入、初始化、销毁等。Bean 可以通过 Singleton、Prototype、Request、Session 等不同的作用域进行配置。