在使用 Spring 的 Web 專案中的一般類別 (即未宣告在 applicationContext.xml 的類別),如何取得由 Spring 實例化出來的物件?
請依照下例步驟執行:
取得 javax.servlet.ServletContext 物件
如果是 struts2 專案,可使用【 org.apache.struts2.ServletActionContext.getServletContext() 】來取得。
取得 org.springframework.context.ApplicationContext 物件
使用【 org.springframework.web.context.support.WebApplicationContextUtils 】類別來取得 WebApplicationContext (繼承自 ApplicationContext) 物件。如下:
WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); // 將第 1 步取得的 ServletContext 物件傳入
透過 ApplicationContext 物件即可取得由 Spring 實例化出來的物件了
例如:HelloService helloService = (HelloService) ac.getBean("helloService");
請依照下例步驟執行:
取得 javax.servlet.ServletContext 物件
如果是 struts2 專案,可使用【 org.apache.struts2.ServletActionContext.getServletContext() 】來取得。
取得 org.springframework.context.ApplicationContext 物件
使用【 org.springframework.web.context.support.WebApplicationContextUtils 】類別來取得 WebApplicationContext (繼承自 ApplicationContext) 物件。如下:
WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); // 將第 1 步取得的 ServletContext 物件傳入
透過 ApplicationContext 物件即可取得由 Spring 實例化出來的物件了
例如:HelloService helloService = (HelloService) ac.getBean("helloService");