Servlet环境下取得spring的ApplicationContext

来源:计算机等级考试    发布时间:2012-08-29    计算机等级考试视频    评论

  项目的应用里重写了 HttpSessionListener,在用户登录超时后需要对数据库进行操作,操作类的 service 自然从 spring 的 application context 里取比较好。
  方法:
  1. 取得 ServletContext,假设实例名为 sc
  2. 调用 Object sc.getAttribute(String) 方法
  3. 参数 String 是什么不确定的时候,考试,大就全列出:
  ServletContext sc = request.getSession().getServletContext();
  Enumeration<String> enu = sc.getAttributeNames();
  while (enu.hasMoreElements()) {
  String name = enu.nextElement();
  Object obj = sc.getAttribute(name);
  System.out.println(name + "/t" + obj.getClass());
  }
  4. 我得到的 obj 的 class 是 name 是 “org.springframework.web.context.WebApplicationContext.ROOT”
  5. 取得 ApplicationContext,并使用:
  ServletContext sc = request.getSession().getServletContext();
  WebApplicationContext ctx = (WebApplicationContext)sc.getAttribute("org.springframework.web.context.WebApplicationContext.ROOT");
  myService = (MyService) ctx.getBean("myService");
  Get Spring ApplicationContext in servlet context.

视频学习

我考网版权与免责声明

① 凡本网注明稿件来源为"原创"的所有文字、图片和音视频稿件,版权均属本网所有。任何媒体、网站或个人转载、链接转贴或以其他方式复制发表时必须注明"稿件来源:我考网",违者本网将依法追究责任;

② 本网部分稿件来源于网络,任何单位或个人认为我考网发布的内容可能涉嫌侵犯其合法权益,应该及时向我考网书面反馈,并提供身份证明、权属证明及详细侵权情况证明,我考网在收到上述法律文件后,将会尽快移除被控侵权内容。

最近更新

社区交流

考试问答