运行spring boot项目时出现bean名称冲突

Sum*_*ood 1 java spring exception spring-boot

背景:我正在一个名为 的项目中工作com.x.myproject。我有另外两个包的依赖关系com.x.documentcom.x.library. 两个包都有相同的类,名称为QueueHelper

现在,在我的项目中,我必须扫描另一个com.x.security内部扫描的包com.x,如下所示:

@SpringBootApplication
@ComponentScan(basePackages = {"com.x"})
@EnableCaching
public class Security {
.......
}
Run Code Online (Sandbox Code Playgroud)

在 com.x.myproject 中

@SpringBootApplication
@ComponentScan(basePackages = {"com.x.myproject","com.x.security"}, excludeFilters={
      @ComponentScan.Filter(type=FilterType.REGEX, pattern="com.x.document.*"),
      @ComponentScan.Filter(type=FilterType.REGEX, pattern="com.x.library.*")}) 
public class MyProject{
.......
}  
Run Code Online (Sandbox Code Playgroud)

excludefilters当我使用时一切正常,com.x.security但我想使用它com.x.myproject

我得到的例外是

Annotation-specified bean name 'queueHelper' for bean class [com.x.library.utils.QueueHelper] conflicts with existing, non-compatible bean definition of same name and class [com.x.document.utils.QueueHelper]
Run Code Online (Sandbox Code Playgroud)

Mur*_*kan 5

我想到了三个答案:

\n\n
    \n
  1. 通过注释com.x.library.utils.QueueHelper指定不同的名称。Spring默认使用简单的类名来命名bean。您可以使用\xc2\xa0 注释一个,另一个使用. 但是,现在您必须在自动装配这些 bean 的每个位置给出一个。com.x.document.utils.QueueHelper@Component@Component('libraryQueueHelper')@Component('documentQueueHelper')@Qualifier(<name>)

  2. \n
  3. 将它们排除在您的模块中,就像您在问题中所做的那样,然后@Bean使用@Configuration. 在第三个模块中使用时,您需要使用 a@Qualifier来自动装配正确的 bean。

  4. \n
  5. 重命名类。在这种情况下这是最好的解决方案,但既然你问了这个问题,我想它是不可行的。

  6. \n
\n