Spring Security 6迁移报错:HttpSecurity中regexMatcher方法无法解析
Spring Security 6 中替代
regexMatcher 的解决方案 在Spring Security 6中,HttpSecurity不再直接提供regexMatcher()方法,需要通过requestMatchers()结合Lambda表达式来配置正则请求匹配规则,修正后的代码如下:
@EnableWebSecurity public class WebSecurityConfig { @Configuration @Order(1) public static class NoFrameOptions { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.requestMatchers(matchers -> matchers.regexMatcher("^/.+$")) .csrf().disable() .headers(headers -> headers.frameOptions(frame -> frame.disable())); return http.build(); } } }
关键说明:
- 用
requestMatchers(matchers -> matchers.regexMatcher("^/.+$"))替代原代码中的http.regexMatcher("^/.+$"),这是Spring Security 6.x版本中配置请求匹配的标准写法。 - 可选优化:headers部分采用Lambda风格配置(如示例中
headers(headers -> headers.frameOptions(frame -> frame.disable()))),这是Spring Security 6推荐的更简洁的配置方式,也可以保留原链式写法headers().frameOptions().disable(),功能一致。
另外,也可以通过显式创建RegexRequestMatcher实例来实现相同效果:
http.requestMatchers(new RegexRequestMatcher("^/.+$", null))
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

