萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 獲取 Spring 注入 Bean 的實作範例

應用場景

在傳統 JSP 頁面(非 Spring MVC View Resolver 渲染)中,需手動從 Spring 容器取得 Bean 實例(如 Service、DAO、工具類)進行業務邏輯處理。

核心程式碼

<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils" %>
<%@ page import="org.springframework.context.ApplicationContext" %>
<%
  // 1. 取得 ServletContext
  ServletContext sc = this.getServletConfig().getServletContext();
  
  // 2. 從 ServletContext 獲取 WebApplicationContext
  ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
  
  // 3. 根據 Bean ID 取得目標 Bean
  MyService myService = (MyService) ac.getBean("myServiceBeanId");
  
  // 4. 呼叫業務方法
  List<Data> list = myService.queryAll();
%>

關鍵類別說明

  • WebApplicationContextUtils:Spring 提供的工具類,從 ServletContext 獲取 WebApplicationContext(Spring 容器的 Web 專用子介面)。
  • getWebApplicationContext(ServletContext):查找 ServletContext 屬性 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE。
  • getBean(String name):從容器取得指定名稱的 Bean,需強制轉型。

前置條件

  1. web.xml 已配置 ContextLoaderListener,啟動時初始化 Spring 容器並綁定至 ServletContext。
  2. 目標 Bean 已在 Spring 設定檔(XML 或 @Configuration)中定義,且 ID 正確。
  3. JSP 執行於同一 Web 應用容器內(共享 ServletContext)。
  4. 進階封裝:工具類簡化調用

    // com.utils.SpringContextHolder.java
    public class SpringContextHolder {
      private static ApplicationContext context;
    
      public static void setApplicationContext(ApplicationContext ac) {
        context = ac;
      }
    
      @SuppressWarnings("unchecked")
      public static <T> T getBean(String name) {
        return (T) context.getBean(name);
      }
    
      public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
      }
    }
    
    // 在 Spring 配置中註冊(實作 ApplicationContextAware)
    @Component
    public class SpringContextInitializer implements ApplicationContextAware {
      @Override
      public void setApplicationContext(ApplicationContext ac) {
        SpringContextHolder.setApplicationContext(ac);
      }
    }

    JSP 中簡化調用

    <%@ page import="com.utils.SpringContextHolder" %>
    <%
      MyService service = SpringContextHolder.getBean("myServiceBeanId");
      // 或直接按類型獲取(單例 Bean)
      MyService service2 = SpringContextHolder.getBean(MyService.class);
    %>

    注意事項

    • 避免濫用:JSP 應為純視圖層,業務邏輯應在 Controller/Service。僅在舊專案遷移、特殊需求(如報表導出、舊式標籤)時使用。
    • 效能:getBean 為單例查找,效能極高,但頻繁在 JSP 呼叫仍建議快取至頁面變數。
    • 型別安全:優先使用 getBean(Class<T>) 避免轉型錯誤。

    現代替代方案

    Spring MVC 專案中,Controller 將資料放入 Model,View(JSP/Thymeleaf)直接透過 EL ${model.data} 存取,完全不需在 JSP 手動取 Bean。建議逐步遷移至 Spring MVC 架構。

copyright © 萬盛學電腦網 all rights reserved