| 接口 | 定位 | 初始化策略 | BeanPostProcessor 註冊 | 典型初始化方式 |
|---|---|---|---|---|
| BeanFactory | 框架內部基礎設施,面向 Spring 本身 | 延遲加載:首次 getBean() 才實例化 |
手動代碼註冊 addBeanPostProcessor() |
new XmlBeanFactory(new ClassPathResource("beans.xml")) |
| ApplicationContext | 面向應用開發者,企業級首選 | 啟動時預實例化所有單例 Bean | 自動掃描 @Component、@Bean、XML 中的 processor bean |
new ClassPathXmlApplicationContext("beans.xml")new AnnotationConfigApplicationContext(AppConfig.class) |
| WebApplicationContext | Web 環境專用,綁定 ServletContext | 依賴 Web 容器啟動,通過 Listener/Servlet 引導 | 繼承 ApplicationContext 能力,額外支持 Web 作用域 | ContextLoaderListener 在 web.xml 配置 |
classpath:、file:、http:、servletContext: 等各類資源,提供 getInputStream()、exists()、getFile() 統一 API。getResource(String location) 根據前綴自動選擇 ClassPathResource、FileSystemResource、ServletContextResource 等實現,上層無感知具體存儲介質。<bean init-method="init" destroy-method="cleanup">@PostConstruct / @PreDestroy(需 InitDestroyAnnotationBeanPostProcessor,Context 自動註冊)。InitializingBean/DisposableBean(強耦合 Spring,不推薦)。<!-- web.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Log4j 啟動順序需早於 ContextLoaderListener -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
關鍵點:load-on-startup 確保 Log4j 配置先於 Spring 容器初始化生效。

理解 BeanFactory vs ApplicationContext 的初始化時機差異、Resource 抽象 解耦存儲細節、WebApplicationContext 與 Servlet 生命周期綁定,是掌握 Spring IoC 容器精髓的三把鑰匙。實際開發中 99% 場景直接使用 AnnotationConfigApplicationContext 或 Spring Boot 自動配置,手動操作 BeanFactory 僅出現在框架擴展或測試場景。