You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成Spring Security时无法使用SessionListener监听SessionCreated事件

Spring Security环境下SessionCreated事件监听失效解决方案

该问题的核心是Servlet容器的会话事件默认未和Spring上下文打通,且自定义监听器未正确注册到Servlet容器,按以下步骤配置即可生效:

步骤1:注册HttpSession事件转发器

Spring Security需要HttpSessionEventPublisher将Servlet容器的会话事件转发到Spring上下文,在你的配置类中添加如下Bean:

@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
    return new HttpSessionEventPublisher();
}

步骤2:选择监听方案(二选一即可)

方案A:使用原生Servlet HttpSessionListener

你之前写的InitHttpSessionListener需要注册到Servlet容器才能生效,无需修改原有监听器代码,添加如下注册Bean即可:

@Bean
public ServletListenerRegistrationBean<InitHttpSessionListener> initSessionListener() {
    ServletListenerRegistrationBean<InitHttpSessionListener> registration = new ServletListenerRegistrationBean<>();
    registration.setListener(new InitHttpSessionListener());
    return registration;
}

你也可以给InitHttpSessionListener添加@WebListener注解,同时在启动类上添加@ServletComponentScan注解完成自动注册。

方案B:使用Spring原生事件监听(更推荐,无需额外注册监听器)

直接基于Spring的SessionCreatedEvent编写监听逻辑,代码更简洁,适配Spring生态:

@Component
public class SessionInitListener {
    @EventListener
    public void onSessionCreated(SessionCreatedEvent event) {
        HttpSession session = event.getSession();
        // 直接在此处初始化购物车、最近浏览列表等属性
        session.setAttribute("userCart", new UserCart());
        session.setAttribute("recentViewList", new ArrayList<>());
    }
}

验证逻辑

配置完成后启动项目,首次访问任意接口时就会触发会话创建事件,你初始化的属性会直接存入HttpSession,在@Controller中可以直接调用request.getSession().getAttribute()获取属性,无需额外判断是否为空。


内容的提问来源于stack exchange,提问作者Borisav Živanović

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 00:45:01