取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);

	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章