`
laodaobazi
  • 浏览: 272761 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

取Spring中Bean方式的解析

阅读更多

     在获取Spring初始的Bean的方法第一想到的就是通过ClassPathXmlApplicationContext类去加载Spring的XML文件,然后通过getBean方法来取得。然而在Web程序中这样get出来的Bean,并不是在web.xml中初始化Spring时候实例化在内存中的Bean,而是再一次实例化的Bean。那么如何在Web工程中去get出来在程序启动时候就实例化好的Bean呢,方法如下:

Servlet中获取Bean:

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//直接在初始化好的所有Bean中去get指定的Bean
		ServletContext context = getServletContext();
	    WebApplicationContext applicationContext =
	            WebApplicationContextUtils.getWebApplicationContext(context);
	    Test t = (Test) applicationContext.getBean("test");
	    
	    //首先重新创建所有的Bean,然后才去抓取指定的Bean
	    ApplicationContext ctx= new ClassPathXmlApplicationContext("applicationContext.xml");
	    Test tt = (Test) ctx.getBean("test"); 
	    
	    //这里配置文件中即使指定scope为singleton,仍为false
	    System.out.println(t==tt);

	}

 

分享到:
评论
1 楼 laodaobazi 2012-04-11  
Spring3之后提供了如下方法来获取Bean,同样可以避免重复加载配置文件的问题
WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();
Service service = (IService)applicationContext.getBean("Service");

相关推荐

Global site tag (gtag.js) - Google Analytics