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

Java 17与Spring 6.0中SessionManagement方法弃用问题求助

Spring 6.0 + Spring Security 6.x 弃用方法替换方案

下面是适配Spring Security 6.x的修正代码,完全替代原代码中的弃用API:

SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        // 会话管理配置,使用lambda替代旧的链式调用
        .sessionManagement(session -> session
            .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .maximumSessions(maxNoOfSessions)
                .expiredUrl("/login")
                .and()
            .invalidSessionUrl("/login")
        )
        // 禁用CSRF
        .csrf(csrf -> csrf.disable())
        // 授权规则配置,替换authorizeRequests为authorizeHttpRequests
        .authorizeHttpRequests(auth -> auth
            // 替换antMatchers为requestMatchers
            .requestMatchers("/**/*.css", "/**/*.ico", "/**/*.svg").permitAll()
            // 所有其他请求需要认证
            .anyRequest().authenticated()
        )
        // 表单登录配置
        .formLogin(form -> form
            .loginPage("/login")
            .failureUrl("/login?error=true") // 补全路径斜杠,确保跳转正确
            .permitAll()
        )
        // 添加认证提供者
        .authenticationProvider(authProvider);

    return http.build();
}

关键修改点说明:

  • authorizeRequests() → authorizeHttpRequests():Spring Security 6.x中authorizeRequests已被标记为弃用,推荐使用authorizeHttpRequests定义HTTP请求的授权规则,API设计更清晰。
  • antMatchers() → requestMatchers():旧的antMatchers方法被弃用,requestMatchers支持更灵活的请求匹配方式,包括Ant路径、正则表达式等,功能完全覆盖前者。
  • 会话管理改用Lambda配置:原代码通过.and()链式调用的方式在Spring Security 6.x中不再推荐,使用sessionManagement(Customizer<SessionManagementConfigurer>)的Lambda形式,代码结构更简洁,避免过多.and()嵌套。
  • 表单登录的Lambda配置:formLogin同样改用Lambda方式配置,替代原有的.and()链式写法,符合Spring Security 6.x的新API风格。
  • 修复了原代码中failureUrl("login?error=true")的路径问题,补上开头的斜杠/,确保跳转路径正确。

内容的提问来源于stack exchange,提问作者Shivam Roy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 18:43:41