萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Spring 容器中獲取 Bean 的五種方式:ApplicationContextAware、WebApplicationContextUtils、繼承支援類與手動初始化

核心介面:ApplicationContext

Spring 容器核心介面,提供 `getBean(name)`、`getBean(type)` 等方法。關鍵在於**如何在非 Spring 管理的類別中拿到這個介面實例**。

方式一:手動初始化 (獨立應用/測試/腳本)

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
MyService bean = ctx.getBean("myService", MyService.class);

適用:main 方法、批次程式、單元測試(無 Spring Test 支援時)。

方式二:WebApplicationContextUtils (Web 環境)

// 在 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`。

方式三:繼承 ApplicationObjectSupport (非 Web)

public class MyHelper extends ApplicationObjectSupport {
    public void doWork() {
        MyService svc = getApplicationContext().getBean(MyService.class);
        svc.execute();
    }
}

Spring 會自動呼叫 `setApplicationContext` 注入容器。**需在 Spring 設定中將此類宣告為 Bean**。

方式四:繼承 WebApplicationObjectSupport (Web)

public class MyWebHelper extends WebApplicationObjectSupport {
    public void doWork() {
        WebApplicationContext wac = getWebApplicationContext();
        MyService svc = wac.getBean(MyService.class);
    }
}

提供 `getServletContext()`、`getTempDir()` 等 Web 便利方法。

方式五:實作 ApplicationContextAware (最通用、推薦)

 T getBean(Class type) {
        return context.getBean(type);
    }
    public static Object getBean(String name) {
        return context.getBean(name);
    }
}
  • 靜態持有 `ApplicationContext`,提供靜態 `getBean` 供任意處呼叫。
  • **必須被 Spring 掃描到** (`@Component` 或 XML ``),否則 `setApplicationContext` 不會被呼叫。
  • 注意:靜態持有可能導致記憶體洩漏,容器關閉時建議清空。

選型建議

場景推薦方式
Spring Boot / 現代 Web 應用**建構子注入** / `@Autowired` 欄位注入 (完全不需手動 getBean)
舊專案非 Spring 管理類別 (工具類、第三方庫回調)ApplicationContextAware 靜態輔助類
Servlet/Filter/Listener 內部WebApplicationContextUtils
獨立 Main 程式/批次/測試手動 `new ClassPathXmlApplicationContext`
需存取 ServletContext 資源繼承 WebApplicationObjectSupport

避坑指南

  • **循環依賴**:A 需 B、B 需 A → 改用 `@Lazy` 或 setter 注入。
  • **原型 Bean**:每次 `getBean` 產生新實例,狀態不共享。
  • **多容器**:父子容器(DispatcherServlet + ContextLoaderListener),`getBean` 會向父委派;同名 Bean 子容器優先。
copyright © 萬盛學電腦網 all rights reserved