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

相关推荐
2601_962066498 小时前
【Sql Server】Update中的From语句,以及常见更新操作方式
android·java·数据库
yaoxin5211238 小时前
507. Java 反射 - 在 BeanFactory 中实现依赖注入
java·开发语言
OPEN-F9 小时前
C++模板教程:变参模板、折叠表达式与SFINAE
java·开发语言·c++
2601_9620722110 小时前
SpringMVC进阶(自定义拦截器以及异常处理)
java
2601_9620738110 小时前
Spring全面详解(基础版)
java·后端·spring
谢亮_vipxieliang11 小时前
ValidX分组验证详解:不同场景使用不同验证规则
java·spring boot·后端·spring cloud·eclipse·hibernate
wuminyu12 小时前
深入剖析 Panama Off-heap 的性能损耗与开销
java·linux·c语言·jvm·c++
pnoker12 小时前
IoT DC3 AI 能力:Agentic Center 的设计与边界
java·人工智能·物联网·大模型·spring ai
凤山老林12 小时前
Spring Boot 集成 Spring Vault:集中式密钥管理与动态凭证轮换
spring boot·后端·spring·vault·集中式秘钥管理
2601_9620711712 小时前
八. Spring Boot2 整合连接 Redis(超详细剖析)
spring boot·redis·后端