下面YJBYS小編為大家整理了Spring獲取Bean四種方法,希望對你有所幫助。更多Java認證考試資訊,盡在應屆畢業生培訓網!
方法一:通過Spring提供的工具類獲取ApplicationContext物件
程式碼:
import pplicationContextUtils;
ApplicationContext ac1 = equiredWebApplicationContext(ServletContext sc)
ApplicationContext ac2 = ebApplicationContext(ServletContext sc)
ean(“beanId”);
ean(“beanId”);
說明:
這種方式適合於採用Spring框架的B/S系統,通過ServletContext物件獲取ApplicationContext物件,然後在通過它獲取需要的類例項。上面兩個工具方式的區別是,前者在獲取失敗時丟擲異常,後者返回null.
其中 servletContext sc 可以具體 換成 ervletContext()或者 ervletContext() 或者 ession()。getServletContext();
另外,由於spring是注入的物件放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 物件:
WebApplicationContext webApplicationContext = (WebApplicationContext) ttribute(_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
方法二:在初始化時儲存ApplicationContext物件
程式碼:
ApplicationContext ac = new FileSystemXmlApplicationContex(“”);
ean(“beanId”);
說明:
這種方式適用於採用Spring框架的獨立應用程式,需要程式通過配置檔案手工初始化Spring的情況。
方法三:繼承自抽象類ApplicationObjectSupport
說明:
抽象類ApplicationObjectSupport提供getApplicationContext()方法,可以方便的獲取到ng初始化時,會通過該抽象類的setApplicationContext(ApplicationContext context)方法將ApplicationContext 物件注入。
方法四:繼承自抽象類WebApplicationObjectSupport
說明:
類似上面方法,呼叫getWebApplicationContext()獲取WebApplicationContext
方法五:實現介面ApplicationContextAware
說明:
實現該介面的setApplicationContext(ApplicationContext context)方法,並儲存ApplicationContext 物件。Spring初始化時,會通過該方法將ApplicationContext 物件注入。
以上方法適合不同的情況,請根據具體情況選用相應的方法。
這裡值得提一點的是,系統中用到上述方法的類實際上就於Spring框架緊密耦合在一起了,因為這些類是知道它們是執行在Spring框架上的,因此,系統中,應該儘量的減少這類應用,使系統儘可能的獨立於當前執行環境,儘量通過DI的方式獲取需要的服務提供者。
然後在Action中編寫如下程式碼得到Context,(我是覆蓋了Struts Action的'setServlet方法,也許還有更好的方法)。
public void setServlet(ActionServlet servlet){
ervlet(servlet);
ServletContext servletContext = ervletContext();
WebApplicationContext wac = equiredWebApplicationContext(servletContext);
// get yours beans
}
我需要在spring的bean中直接獲取,這下可和我們常規的操作有些不同,因為spring的bean都是pojo的。根本見不著servletconfig和servletcontext的影子。
這裡我需要指出spring給我們提供了兩個介面:letContextAware和
letConfigAware.我們可以讓我們的bean實現上邊的任何一個介面就能獲取到servletContext了 .
程式碼如下:
public class DicBean implements ServletContextAware{
private ServletContext servletContext;
public void setServletContext(ServletContext sc) {
letContext=sc;
tln(“專案的絕對路徑為:”+ealPath(“/”));
}
}
Copyright ©2024 才華齋 All Rights Reserved.