`

Spring中获取ApplicationContext

阅读更多

在用到spring的项目中往往需要获取到ApplicationContext,网上随便一搜也有很多,无非就是以下五种:

  1. ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
  2. ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
    ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
  3. 继承自抽象类ApplicationObjectSupport
  4. 继承自抽象类WebApplicationObjectSupport
  5. 实现接口ApplicationContextAware

其实有一种更好更方便的方法,那就是

WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();

 这种方法与上面后三种相比好处就不用多说了,与第一种相比,不需要重新加载一次xml配置文件,节省资源和时间。与第二种相比不仅不需要ServletContext ,速度上也有明显优势,几乎不需要消耗时间。亲们可以尝试下!

1
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics