在獲取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);
}