Spring中获取ApplicationContext
程序员文章站
2022-05-23 13:37:24
...
在用到spring的项目中往往需要获取到ApplicationContext,网上随便一搜也有很多,无非就是以下五种:
- ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
-
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); - 继承自抽象类ApplicationObjectSupport
- 继承自抽象类WebApplicationObjectSupport
- 实现接口ApplicationContextAware
其实有一种更好更方便的方法,那就是
WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();
这种方法与上面后三种相比好处就不用多说了,与第一种相比,不需要重新加载一次xml配置文件,节省资源和时间。与第二种相比不仅不需要ServletContext ,速度上也有明显优势,几乎不需要消耗时间。亲们可以尝试下!