close

在使用 Spring 的 Web 專案中的一般類別 (即未宣告在 applicationContext.xml 的類別),如何取得由 Spring 實例化出來的物件?

請依照下例步驟執行:

  1. 取得 javax.servlet.ServletContext 物件
    如果是 struts2 專案,可使用【 org.apache.struts2.ServletActionContext.getServletContext() 】來取得。

  2. 取得 org.springframework.context.ApplicationContext 物件
    使用【 org.springframework.web.context.support.WebApplicationContextUtils 】類別來取得 WebApplicationContext (繼承自 ApplicationContext) 物件。如下:

    WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); // 將第 1 步取得的 ServletContext 物件傳入


  3. 透過 ApplicationContext 物件即可取得由 Spring 實例化出來的物件了
    例如:HelloService helloService = (HelloService) ac.getBean("helloService");

 

要特別注意的是,千萬不要在 spring  的 web 專案中的一般類別裏使用 org.springframework.context.support.ClassPathXmlApplicationContext("applicationContext.xml") 來實例化 ApplicationContext,因為這樣會讓 spring 從讀取 applicationContext.xml 開始再建立一整套的 spring 實例物件,如此一來,一旦這個類別/物件被反覆呼叫,那就會不斷地執行 spring 的初始化 (開啟 xml、建立物件),漸漸的就會耗盡 server 的 memory 或者是 io 資源 (會出現開太多檔案的錯誤)。因此,如果要在 web 專案中取得 ApplicationContext,請使用 WebApplicationContextUtils 來抓取。

arrow
arrow
    全站熱搜

    大笨鳥 發表在 痞客邦 留言(0) 人氣()