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

Spring Boot:如何禁用嵌入式服务器的Session Handler?

禁用Spring Boot嵌入式Jetty的Session支持

方法1:通过配置属性快速禁用

Spring Boot提供了开箱即用的配置项,可全局禁用Session支持,无需手动修改Jetty内部Handler:

  • 在application.properties中添加:
    server.servlet.session.enabled=false
    
  • 或在application.yml中配置:
    server:
      servlet:
        session:
          enabled: false
    

该配置会让Spring自动跳过Session相关组件的初始化,包括Jetty的Session Handler,不会触发上下文启动异常。

方法2:正确定制Jetty服务器(避免直接移除Handler)

若需更精细控制,不要直接删除Session Handler(会破坏Spring Boot预设的Jetty结构),而是通过禁用SessionManager来实现需求:

import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JettySessionConfig {
    @Bean
    public WebServerFactoryCustomizer<JettyServletWebServerFactory> jettySessionCustomizer() {
        return factory -> {
            factory.addServerCustomizers(server -> {
                // 保留Session Handler结构但禁用Session功能
                server.getSessionHandler().setSessionManager(null);
            });
        };
    }
}

直接移除Session Handler会导致Spring上下文初始化时依赖缺失,而设置sessionManager为null既能禁用Session,又能维持Jetty服务器的正常结构。

方法3:针对Web MVC层禁用Session(无状态API场景)

如果应用是纯无状态API,可在WebMvc配置中标记所有请求无需Session:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.SessionManagementConfigurer;

@Configuration
public class WebMvcSessionConfig implements WebMvcConfigurer {
    @Override
    public void configureSessionManagement(SessionManagementConfigurer configurer) {
        configurer.disable();
    }
}

该配置会让Spring MVC不再创建或尝试获取Session,配合前面的Jetty配置可彻底关闭Session相关功能。

内容的提问来源于stack exchange,提问作者Anonymous Person

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 00:35:54