ConflictingBeanDefinitionException: Annotation-specified bean name ‘XXX‘ for bean class

报错信息

Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'mybatisInterceptor' for bean class [com.sinandata.service.commons.config.MybatisInterceptor] conflicts with existing, non-compatible bean definition of same name and class [com.sinandata.kg.report.config.MybatisInterceptor]
	at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:349)
	at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:287)
	at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:132)
	at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:296)
	at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:250)
	at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:207)
	at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:175)

这个错误是因为在 Spring context 中有两个名称相同但类不兼容的 bean 定义而引起的。在您的项目中,有两个 XXX类被定义,并且都使用了相同的 bean 名称XXX,这导致了冲突。

如果该两个Bean都是你自己定义的,可以通过以下几种方式解决:

  1. 修改 bean 名称 - 将其中一个 MybatisInterceptor 的 bean 名称修改为不同的名称,避免名称冲突。

  2. 区分类名或包名 - 将两个 MybatisInterceptor 类的类名或所在包名进行区分,以避免类名冲突。

  3. 使用 @Qualifier 注解 - 在注入 bean 的过程中,使用 @Qualifier 注解指定要注入的具体 bean,而不是使用默认名称。例如:@Autowired @Qualifier(“mybatisInterceptor1”) private MybatisInterceptor mybatisInterceptor;

如果其中一个是外部Jar包自带的依赖Bean,则通过以下方式排除Bean:
在启动类上加上注解
@ComponentScan( excludeFilters = [ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = [MybatisInterceptor.class()])])

解释:
 在 Spring 框架中,@ComponentScan 注解用于搜索标有 @Component、@Service、@Controller、@Repository 等注解的类,并将它们注册为 Spring 容器中的 Bean。有时候,您可能希望排除某些类,比如第三方库的类或者框架自带的类,以避免造成冲突。

 excludeFilters 属性是 @ComponentScan 注解的一个元素,可以用来指定要排除的类。其中,Filter 是一个枚举类型,包含四个过滤器类型:ANNOTATION、ASSIGNABLE_TYPE、ASPECTJ 和 CUSTOM。

 在提供的代码中,excludeFilters 属性使用了 ASSIGNABLE_TYPE 类型的过滤器,并指定了一个名为 MybatisInterceptor 的类。这意味着,如果某个类和 MybatisInterceptor 类型相同,它将被排除在扫描范围外,不会被注册为 Spring 容器中的 Bean。

猜你喜欢

转载自blog.csdn.net/java_cpp_/article/details/130968149
今日推荐