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