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 。当遇到同样名字的时候,是否允许覆盖注册

相关推荐
一直不明飞行1 小时前
Java的equals(),hashCode()应该在什么时候重写
java·开发语言·jvm
REDcker1 小时前
有限状态机与状态模式详解 FSM建模Java状态模式与C++表驱动模板实践
java·c++·状态模式
你的保护色2 小时前
【无标题】
java·服务器·网络
basketball6162 小时前
C++ 构造函数完全指南:从入门到进阶
java·开发语言·c++
淘矿人2 小时前
Claude辅助DevOps实践
java·大数据·运维·人工智能·算法·bug·devops
小江的记录本3 小时前
【Java基础】泛型:泛型擦除、通配符、上下界限定(附《思维导图》+《面试高频考点清单》)
java·数据结构·后端·mysql·spring·面试·职场和发展
来恩10033 小时前
请求转发与响应重定向的使用
java
@杰克成3 小时前
Java学习30
java·开发语言·学习
次元工程师!3 小时前
LangFlow开发(三)—Bundles组件架构设计(3W+字详细讲解)
java·前端·python·低代码·langflow
oddsand15 小时前
Redis网络模型
java·数据库·redis