首页 > 解决方案 > Spring 依赖项未嵌入 HTTPSessionListener

问题描述

我想通过下面的链接在我的自定义 HTTPSessionListener 实例中注入 spring 依赖项。如果我从 web.xml 中删除条目 sessionDestroyed 方法不会被调用,但是当 web.xml 方法中的条目被调用但 XUSerMgr 的依赖项是无效的。

如何使用 Spring 将依赖项注入 HttpSessionListener?enter code here戒指

@Component
public class RangerHttpSessionListener implements HttpSessionListener,ApplicationContextAware {

    @Autowired
    XUserMgr xUserMgr;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (applicationContext instanceof WebApplicationContext) {
            ((WebApplicationContext) applicationContext).getServletContext().addListener(this);
        } else {
            //Either throw an exception or fail gracefully, up to you
            throw new RuntimeException("Must be inside a web application context");
        }
    }

    private static CopyOnWriteArrayList<HttpSession> listOfSession = new CopyOnWriteArrayList<HttpSession>();

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        listOfSession.add(event.getSession());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        if (!listOfSession.isEmpty()) {
            updateIsActiveStatusForAuthSession(event.getSession());
            listOfSession.remove(event.getSession());
        }
    }

    private void updateIsActiveStatusForAuthSession(HttpSession session) {
        xUserMgr.updateIsActiveStatusOfLoggedInUserWithHTTPSession(session.getId(),1);
    }

    public static CopyOnWriteArrayList<HttpSession> getActiveSessionOnServer() {
        return listOfSession;
    }

}

我的 web.xml 中有以下条目。> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <listener> <listener-class>org.apache.ranger.security.listener.RangerHttpSessionListener</listener-class> </listener>

标签: spring-security

解决方案


推荐阅读