Spring的自动装配在session监听器失效

先看代码

package com.oa.listener;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.beans.factory.annotation.Autowired;

import com.oa.service.SystemManagementService;

/**
 * 
 * @author: zhao
 * @time: 2016年5月3日
 * 
 * @description:session监听器,在session销毁的时候,执行数据库操作。更改user_login的在线状态
 * 
 */
public class SessionListener implements HttpSessionListener {
    @Autowired
    private SystemManagementService service;

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        System.out.println("Session:" + session.hashCode());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        String login_id = (String) session.getAttribute("id");
        if (login_id != null && !"".equals(login_id)) {
            // 更改在线状态
            session.setAttribute("id", "");
            service.doLoginAndLogout(login_id, false);
        }
        System.out.println("Session监听器运行。。。");
    }

}

本栏想的挺好的,把业务逻辑层的接口通过spring的自动装配给注入,然后用就可以了。结果发现总是报错。就说我空指针,找来找去,除了bean以外,我也没写什么东西。

解决方法,不用注解那些东西了,我们通过上下文获取ApplicationContext,然后通过bean name获取bean。

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        String login_id = (String) session.getAttribute("id");
        if (login_id != null && !"".equals(login_id)) {
            // 更改在线状态
            session.setAttribute("id", "");
            ApplicationContext context=WebApplicationContextUtils.getRequiredWebApplicationContext(session.getServletContext());
            SystemManagementService service=(SystemManagementService) context.getBean("systemManagementService");
            service.doLoginAndLogout(login_id, false);
        }
        System.out.println("Session监听器运行。。。");
    }

 

posted @ 2016-05-03 20:10  假寐的我  阅读(1280)  评论(0编辑  收藏  举报