项目的应用里重写了 HttpSessionListener,在用户登录超时后需要对数据库进行操作,操作类的 service 自然从 spring 的 application context 里取比较好。
方法:
1. 取得 ServletContext,假设实例名为 sc
2. 调用 Object sc.getAttribute(String) 方法
3. 参数 String 是什么不确定的时候,就全列出:
4. 我得到的 obj 的 class 是 name 是 “org.springframework.web.context.WebApplicationContext.ROOT”
5. 取得 ApplicationContext,并使用:
Get Spring ApplicationContext in servlet 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());
- }
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.
更好的方法:
- ServletContext sc = getServletContext();
- WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
- context.getBean("xxx");