Servlet環(huán)境下取得spring的ApplicationContext

字號(hào):

項(xiàng)目的應(yīng)用里重寫(xiě)了 HttpSessionListener,在用戶(hù)登錄超時(shí)后需要對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作,操作類(lèi)的 service 自然從 spring 的 application context 里取比較好。
    方法:
    1. 取得 ServletContext,假設(shè)實(shí)例名為 sc
    2. 調(diào)用 Object sc.getAttribute(String) 方法
    3. 參數(shù) String 是什么不確定的時(shí)候,考試,大就全列出:
    ServletContext sc = request.getSession().getServletContext();
    Enumeration 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.