could not be registered. A bean with that name has already been defined in file

今天在使用SpringBoot中的拦截器的功能是遇到了如下的BUG,为了让屏幕前的您尽快排雷,特此记录一下 ,报错信息如下:

java 复制代码
Description:

The bean 'noLoginInterceptor', defined in class path resource [com/zwl/crm/config/MyConfig.class], could not be registered. A bean with that name has already been defined in file [E:\workplace\MyProject\crm\target\classes\com\zwl\crm\Interceptor\NoLoginInterceptor.class] and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

简单看一下报错信息,说"could not be registered",注入失败"?我的代码如下图:

首先想到的是@Bean没有被识别,于是改变写法使用IOC注入:

项目成功的运行起来了,很纳闷,这是怎么回事?仔细阅读报错信息" A bean with that name has already been defined in file",说明Bean被重复注册了,通过查找资料得知:

在启动类上加@MapperScan("需要扫描的包路径"),在项目启动时会自动将扫描到的Bean进行注册,我的是在配置拦截器时加了@Component

这个和配置类中的@Bean重复的为一个Bean进行注册,到此彻底明白了。

解决方案总结:

1.删除拦截器类级别的@Component注解

2.将配置类中的@Bean改为IOC自动注入

3.application配置文件里加一行:spring.main.allow-bean-definition-overriding: true 。当遇到同样名字的时候,是否允许覆盖注册

相关推荐
一条泥憨鱼几秒前
拦截器与过滤器:一次请求穿过 Spring 时,会先经过谁呢
java·开发语言·后端·spring
Shaoshing2 分钟前
二分模板(左右查询)
java·算法·二分
小七在进步3 分钟前
C++内存管理:new/delete vs malloc/free深度解析
android·java·c++
yuniko-n4 分钟前
【JUC】公平锁与非公平锁
java
郑州光合科技余经理6 分钟前
本地生活服务系统:预约状态和进度通知接口怎么拆
java·开发语言·前端·javascript·后端·php·生活
靠沿10 分钟前
MySQL数据库基础——事务
java·数据库·mysql
RuoyiOffice16 分钟前
Springboot + Vue3 + FormCreate表单引擎,直接用AI对话进行单据设计,告别拖拽画表单
spring boot·低代码·vue3·sse·formcreate·ruoyi office·ai表单
Joy T6 小时前
Agent 确定性上下文设计:从 Prompt 参数注入到能力分层
java·开发语言·微服务·架构·prompt·agent context
m0_587383009 小时前
广州 24 小时自助健身房解决方案技术实现与实战指南
java·spring·小程序·架构·需求分析
·云扬·9 小时前
Prompt 工程与安全:从 System 设计到注入防御
java·人工智能·安全·ai·prompt