Spring 容器核心介面,提供 `getBean(name)`、`getBean(type)` 等方法。關鍵在於**如何在非 Spring 管理的類別中拿到這個介面實例**。
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
MyService bean = ctx.getBean("myService", MyService.class);
適用:main 方法、批次程式、單元測試(無 Spring Test 支援時)。
// 在 Servlet、Filter、Listener、Controller、JSP 中
ServletContext sc = request.getServletContext(); // 或 getServletConfig().getServletContext()
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
// 或允許 null
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
MyService bean = ctx.getBean(MyService.class);
原理:`ContextLoaderListener` 啟動時將 `WebApplicationContext` 存入 `ServletContext` 屬性 `WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE`。
public class MyHelper extends ApplicationObjectSupport {
public void doWork() {
MyService svc = getApplicationContext().getBean(MyService.class);
svc.execute();
}
}
Spring 會自動呼叫 `setApplicationContext` 注入容器。**需在 Spring 設定中將此類宣告為 Bean**。
public class MyWebHelper extends WebApplicationObjectSupport {
public void doWork() {
WebApplicationContext wac = getWebApplicationContext();
MyService svc = wac.getBean(MyService.class);
}
}
提供 `getServletContext()`、`getTempDir()` 等 Web 便利方法。
T getBean(Class type) {
return context.getBean(type);
}
public static Object getBean(String name) {
return context.getBean(name);
}
}
| 場景 | 推薦方式 |
|---|---|
| Spring Boot / 現代 Web 應用 | **建構子注入** / `@Autowired` 欄位注入 (完全不需手動 getBean) |
| 舊專案非 Spring 管理類別 (工具類、第三方庫回調) | ApplicationContextAware 靜態輔助類 |
| Servlet/Filter/Listener 內部 | WebApplicationContextUtils |
| 獨立 Main 程式/批次/測試 | 手動 `new ClassPathXmlApplicationContext` |
| 需存取 ServletContext 資源 | 繼承 WebApplicationObjectSupport |