怎么获取Spring的ApplicationContext(二)

2014-11-23 21:55:46 · 作者: · 浏览: 10
T_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
  • }

    哈哈,明白了吧,它和我们自己实现的方法是一样的。

    这种方法一般用在你自己定义了一个Listener并且实现了ServletContextListener接口,在web.xml中你需要把这个Listener配置好

    	
                        
    
    	
                        
    	  
                         
                          cn.itcast.oa.Utils.InitListener
                         
    	
                        
    实现这个监听器的类如下:

    public class InitListener implements ServletContextListener {
    
    //启动时,为最大的作用于初始化
    	public void contextInitialized(ServletContextEvent sce) {
    		// 获取容器与相关的Service对象
    		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
    		PrivilegeService privilegeService = (PrivilegeService) ac.getBean("privilegeServiceImpl");
    
    		// 准备数据:topPrivilegeList
    		List
                        
                          topPrivilegeList = privilegeService.findTopList();
    		sce.getServletContext().setAttribute("topPrivilegeList", topPrivilegeList);
    		System.out.println("------------> 已准备数据 <------------");
    	}
    
    	public void contextDestroyed(ServletContextEvent arg0) {
    
    	}
    }
    
                        


    还有一种简单的

    代码:
    ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
    ac.getBean("beanId");
    说明:这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。

    然后。。。。。获取的这个ApplicationContext对象后你就可以getBean()了。。。。。啦啦

    参考 http://www.blogjava.net/Todd/archive/2010/04/22/295112.html