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

Spring 6 MVC配置自定义登录页后出现mvcHandlerMappingIntrospector缺失错误

问题分析与解决方案

问题描述

使用Tomcat 10.1.24 + JDK 21,依赖版本如下:

<spring.version>6.0.10</spring.version>
<spring.security.version>6.0.4</spring.security.version>
<spring.data.version>3.1.1</spring.data.version>

原配置下项目可正常使用Spring默认登录页,登录后能访问首页,但修改security-config.xml配置自定义登录页后,出现如下错误:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mvcHandlerMappingIntrospector' available: A Bean named mvcHandlerMappingIntrospector of type org.springframework.web.servlet.handler.HandlerMappingIntrospector is required to use MvcRequestMatcher. Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext.

核心原因

Spring Security使用MvcRequestMatcher时需要依赖Spring MVC的HandlerMappingIntrospector bean,但当前Spring Security和Spring MVC的配置不在同一个ApplicationContext中,导致Security无法找到该bean。

解决方案

方案1:确保Spring Security与Spring MVC共享ApplicationContext

如果通过web.xml配置项目:

  • 检查是否将Spring Security配置文件(如security-config.xml)加入DispatcherServlet的上下文配置中,而非仅通过ContextLoaderListener加载。
  • 示例修改:在web.xml的DispatcherServlet配置里添加Security配置:
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc.xml, /WEB-INF/security-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

同时移除ContextLoaderListener中对security-config.xml的引用,避免重复加载。

方案2:手动注册mvcHandlerMappingIntrospector Bean

如果暂时无法调整上下文配置,可在Spring MVC或Security的配置文件中手动定义该bean:

<bean id="mvcHandlerMappingIntrospector" class="org.springframework.web.servlet.handler.HandlerMappingIntrospector"/>

若使用Java配置,添加如下代码:

@Bean
public HandlerMappingIntrospector mvcHandlerMappingIntrospector() {
    return new HandlerMappingIntrospector();
}

方案3:替换MvcRequestMatcher为AntPathRequestMatcher(不推荐)

如果配置中使用了MvcRequestMatcher,可临时替换为AntPathRequestMatcher绕过依赖,但MvcRequestMatcher能更好适配Spring MVC路由规则,因此优先推荐前两种方案。

内容的提问来源于stack exchange,提问作者Sariq Shaikh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:01:05