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

Spring Boot从3.0.8升级到3.0.9后SecurityFilterChain无法实例化

解决思路

问题根源

Spring Boot 3.0.9对应的Spring Security 6.0.7版本强化了请求匹配器的类型校验逻辑,原配置中**多次拆分调用authorizeHttpRequests()**会导致框架无法确定请求匹配器的上下文归属(是Spring MVC模式还是Ant路径模式),同时未明确指定匹配器类型,触发了新的校验报错。

具体修复方案

1. 合并授权规则配置块

不要拆分多次调用authorizeHttpRequests(),改用Lambda风格将所有授权规则集中在一个配置块内,避免上下文冲突。

2. 明确指定请求匹配器类型

对于Spring MVC端点,使用MvcRequestMatcher(需依赖HandlerMappingIntrospector);如果是非MVC端点(如静态资源、自定义Filter接管的路径),则使用AntPathRequestMatcher。

修改后的示例代码

import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;

@Autowired
private HandlerMappingIntrospector handlerMappingIntrospector;

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    MvcRequestMatcher.Builder mvcMatcher = new MvcRequestMatcher.Builder(handlerMappingIntrospector);

    http
        .authorizeHttpRequests(auth -> auth
            // 公开路径
            .requestMatchers(mvcMatcher.pattern("/"), mvcMatcher.pattern("/favicon.ico"), mvcMatcher.pattern("/v3/api-docs*"))
            .permitAll()
            // 日志查看路径权限
            .requestMatchers(mvcMatcher.pattern("/log"))
            .hasAnyRole(ROLE_LOGVIEWER)
            // 健康检查路径权限
            .requestMatchers(mvcMatcher.pattern("/manage/health"))
            .hasAnyRole(ROLE_HEALTH)
            // 其余路径默认权限
            .anyRequest()
            .hasAnyRole(ROLE_USER)
        )
        .httpBasic();

    return http.build();
}

额外注意事项

  • 不要手动指定Spring Security版本,依赖Spring Boot Parent的自动版本管理即可,确保版本与Spring Boot 3.0.9完全匹配,避免冲突。
  • 若存在非Spring MVC处理的路径,可替换为AntPathRequestMatcher,示例:
    .requestMatchers(new AntPathRequestMatcher("/custom-static/**"))
    

内容的提问来源于stack exchange,提问作者Thilo Schwarz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:53:13