代碼:
application context AC = new file systemxmlaplicationcontext(" application context . XML ");
AC . get bean(" beanId ");
註意:該方法適用於采用Spring框架的獨立應用,需要程序通過配置文件手動初始化Spring。
2.方法二:通過Spring提供的工具類獲取ApplicationContext對象。
代碼:
import org . spring framework . web . context . support . webapplicationcontextutils;
application context AC 1 = webapplicationcontextutils . getrequiredwebapplicationcontext(servlet context sc);
application context ac2 = webapplicationcontextutils . getwebapplicationcontext(servlet context sc);
AC 1 . get bean(" beanId ");
ac2 . get bean(" beanId ");
描述:
該方法適用於采用Spring框架的B/S系統。通過ServletContext對象獲取ApplicationContext對象,然後通過它獲取所需的類實例。
以上兩種工具的區別在於,前者在采集失敗時拋出異常,後者返回null。
ServletContext sc可以改成servlet.getServletContext()或者this.getServletContext()或者request。getSession()。getServletContext();另外,由於spring是放在ServletContext中的註入對象,因此,可以直接從ServletContext中取出WebApplicationContext對象:WebApplicationContext WebApplicationContext =(WebApplicationContext)。servlet context . get attribute(WebApplicationContext。根_ WEB _應用程序_上下文_屬性);
3.方法3:從抽象類ApplicationObjectSupport繼承。
描述:抽象類ApplicationObjectSupport提供了getApplicationContext()方法,可以很容易地得到ApplicationContext。
Spring初始化時,ApplicationContext對象將通過抽象類的setApplicationContext(application context)方法註入。
4.方法4:從抽象類WebApplicationObjectSupport繼承。
描述:與上述方法類似,調用getWebApplicationContext()獲取WebApplicationContext。
5.方法5:實現接口ApplicationContextAware
描述:實現接口的setApplicationContext(Application Context Context)方法,保存應用上下文對象。
當Spring初始化時,ApplicationContext對象將通過該方法註入。