解决异常:ShiroRequestMappingConfig required a single bean, but 2 were found...

2025-09-17后端1 分钟122 次阅读
AI 摘要鱼粮不足,AI 今天先歇着 · 正文在下面

问题

在将 Shiro 2.0.1 与 Spring Boot 3(Jakarta EE)和 Actuator 集成时,可能会遇到如下启动报错:

java 复制代码
Parameter 0 of constructor in org.apache.shiro.spring.web.config.ShiroRequestMappingConfig 
required a single bean, but 2 were found:
 - requestMappingHandlerMapping: defined by WebMvcAutoConfiguration
 - controllerEndpointHandlerMapping: defined by WebMvcEndpointManagementContextConfiguration

意思就是 ShiroRequestMappingConfig 这个类需要 RequestMappingHandlerMapping 的bean,但是扫描到两个,要么改源码,不合适,要么自定义一个bean,通过 @Primary 标记主bean,优先被引用。这样就修复了错误

解决方案

在 Shiro 配置类中,增加一个@Primary的 Bean:

java 复制代码
@Bean
@Primary
public RequestMappingHandlerMapping overridedRequestMappingHandlerMapping() {
    RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping();
    mapping.setUrlPathHelper(new ShiroUrlPathHelper());
    return mapping;
}
  • @Primary 表示 Spring 在自动注入时优先选择这个 Bean
  • 使用 ShiroUrlPathHelper 保持与 Shiro 的路径处理一致
  • 避免 Shiro 自动配置注入到 Actuator 的 controllerEndpointHandlerMapping
觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句