Servlet 环境下取得 spring 的 ApplicationContext

本文介绍了一种在项目的应用中通过重写HttpSessionListener并在用户登录超时后对数据库进行操作的方法。具体步骤包括如何从ServletContext获取Spring的ApplicationContext,并从中取出所需的服务对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目的应用里重写了 HttpSessionListener,在用户登录超时后需要对数据库进行操作,操作类的 service 自然从 spring 的 application context 里取比较好。


方法:

1. 取得 ServletContext,假设实例名为 sc
2. 调用 Object sc.getAttribute(String) 方法
3. 参数 String 是什么不确定的时候,就全列出:
  1.         ServletContext sc = request.getSession().getServletContext();
  2.         Enumeration<String> enu = sc.getAttributeNames();
  3.         while (enu.hasMoreElements()) {
  4.             String name = enu.nextElement();
  5.             Object obj = sc.getAttribute(name);
  6.             System.out.println(name + "/t" + obj.getClass());
  7.         }
4. 我得到的 obj 的 class 是 name 是 “org.springframework.web.context.WebApplicationContext.ROOT”
5. 取得 ApplicationContext,并使用:
  1.         ServletContext sc = request.getSession().getServletContext();
  2.         WebApplicationContext ctx = (WebApplicationContext)sc.getAttribute("org.springframework.web.context.WebApplicationContext.ROOT");
  3.         myService = (MyService) ctx.getBean("myService");

Get Spring ApplicationContext in servlet context.


更好的方法:
  1. ServletContext sc = getServletContext();
  2. WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
  3. context.getBean("xxx");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值