項目的應用裡重寫了 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.
更好的方法:
- ServletContext sc = getServletContext();
- WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
- context.getBean("xxx");