升级Spring应用至Java 19后,IDE提示.formLogin().and().exceptionHandling()已废弃?
Spring Security 6.1+ 废弃链式配置的解决方案
你遇到的是Spring Security 6.1版本开始的API变更——原来的链式.and()配置方式(包括formLogin().and().exceptionHandling()这类写法)被标记为废弃并计划移除,替代方案是使用Lambda DSL配置风格,不再依赖.and()来衔接不同的安全规则块。
原来的废弃写法示例
http .formLogin() .loginPage("/login") .permitAll() .and() .exceptionHandling() .authenticationEntryPoint(customEntryPoint) .and() .authorizeHttpRequests(auth -> auth .requestMatchers("/public/**").permitAll() .anyRequest().authenticated() );
修改后的Lambda风格写法
http .authorizeHttpRequests(auth -> auth .requestMatchers("/public/**").permitAll() .anyRequest().authenticated() ) .formLogin(form -> form .loginPage("/login") .permitAll() ) .exceptionHandling(exceptions -> exceptions .authenticationEntryPoint(customEntryPoint) );
核心变化说明
- 每个配置块(如
formLogin、exceptionHandling)都通过传入Lambda表达式完成内部配置,无需再用.and()切换上下文 - 这种写法更直观,避免了链式调用中可能出现的上下文混淆问题,是Spring Security官方推荐的新配置方式
内容的提问来源于stack exchange,提问作者Jaiylon
相关产品推荐
相关产品推荐

