java 监听器Listener中注入service

直接在Listener中使用@Autowired或@Resource注入,你会发现注入不了,会报空指针,所以只能手动注入,具体代码如下:

se 为HttpSessionEvent

ServletContext sc = se.getSession().getServletContext();
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
OnlineUserService onlineUserService = applicationContext.getBean(OnlineUserService.class);

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.wondersgroup.mzj.pc.service.impl.OnlineUserService;

public class OnlineUserListener implements HttpSessionListener{
	public void sessionCreated(HttpSessionEvent se) {
		System.out.println("session创建");
	}

	public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext sc = se.getSession().getServletContext();
        ApplicationContext applicationContext =WebApplicationContextUtils.getWebApplicationContext(sc);
        OnlineUserService onlineUserService = applicationContext.getBean(OnlineUserService.class);
        doSomething("...");
       
	}
   
}

仅供参考,交流群:700637673,共勉!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章