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

相关推荐
r***12385 分钟前
SpringBoot最佳实践之 - 使用AOP记录操作日志
java·spring boot·后端
间彧9 分钟前
Java进程内存深度解析:从JVM组件内存到RSS的全面视角
java
间彧15 分钟前
对比GraalVM Native Image与传统JVM,在内存管理方面各自适合哪些具体业务场景?
java
daidaidaiyu26 分钟前
Spring IOC 源码学习一 基本姿势
java·spring
间彧33 分钟前
Spring AOT + GraalVM Native Image:云原生Java的效能引擎
spring
LSL666_40 分钟前
SpringBoot自动配置类
java·spring boot·后端·自动配置类
q***78371 小时前
Spring Boot 3.X:Unable to connect to Redis错误记录
spring boot·redis·后端
甜鲸鱼1 小时前
Java与MySQL中的枚举(Enum)
java·mysql
xxxxxxllllllshi1 小时前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
t***26591 小时前
SpringBoot + vue 管理系统
vue.js·spring boot·后端