1、在初始化时保存ApplicationContext对象 代码:
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId");
说明:这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。
2、通过Spring提供的工具类获取ApplicationContext对象
WebApplicationContextUtils
.getWebApplicationContext(ContextLoaderListener
.getCurrentWebApplicationContext().getServletContext())
ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息,一个servlet可以使用getServletContext()方法得到web应用的servletContext
即而使用getServletContext的一些方法来获得一些值.