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,共勉!

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