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

Spring Security 6.1自定义DSL如何适配Lambda DSL?

关于Spring Security 6.1自定义DSL的Lambda适配方案

目前Spring Security 6.1及现有稳定版本中,确实没有为自定义AbstractHttpConfigurer提供原生的Lambda链式调用替代方案——官方默认的Lambda DSL仅覆盖框架内置配置器,自定义配置器仍需依赖apply()+and()模式,或拆分语句配置。

若想规避废弃的and()方法,同时保持代码连贯性,有两种可行替代方式:

  • 拆分配置语句:将自定义配置器的配置单独成段,不强行链式调用,示例如下:
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 应用并获取自定义配置器实例
        MyCustomConfigurer customConfig = http.apply(new MyCustomConfigurer()).get();
        customConfig.setSomeProperty("value");
        // 继续内置配置
        http.authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/login")
            );
        return http.build();
    }
    
  • 扩展自定义配置器API:在自定义AbstractHttpConfigurer实现中添加返回HttpSecurity的方法,替代原生and()的作用,示例如下:
    public class MyCustomConfigurer extends AbstractHttpConfigurer<MyCustomConfigurer, HttpSecurity> {
        private String someProperty;
    
        public MyCustomConfigurer someProperty(String value) {
            this.someProperty = value;
            return this;
        }
    
        // 自定义方法,返回HttpSecurity支持链式调用
        public HttpSecurity and() {
            return getBuilder();
        }
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
            // 自定义配置逻辑
        }
    }
    
    配置时即可使用:
    http.apply(new MyCustomConfigurer())
        .someProperty("value")
        .and() // 调用自定义的and(),而非废弃的SecurityConfigurerAdapter::and
        .authorizeHttpRequests(auth -> auth.anyRequest().authenticated());
    

官方当前文档确实存在滞后,针对自定义DSL的Lambda适配方案尚未跟进,后续版本可能补充相关支持,但当前版本没有遗漏的原生机制可直接实现自定义配置器的Lambda链式调用。

内容的提问来源于stack exchange,提问作者Nick McKinney

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:49:53