【问题标题】:bean name conflict while running the spring boot project运行spring boot项目时bean名称冲突
【发布时间】:2018-05-12 08:50:12
【问题描述】:

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

现在,在我的项目中,我必须扫描另一个包com.x.security,它在内部扫描com.x,类似这样:

@SpringBootApplication
@ComponentScan(basePackages = {"com.x"})
@EnableCaching
public class Security {
.......
}

在 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{
.......
}  

当我在com.x.security 中使用excludefilters 时一切正常,但我想在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]

【问题讨论】:

标签: java spring spring-boot exception


【解决方案1】:

我想到了三个答案:

  1. 通过@Component 注释为com.x.library.utils.QueueHelpercom.x.document.utils.QueueHelper 赋予不同的名称。 Spring 将默认使用简单的类名来命名 bean。您可以用@Component('libraryQueueHelper') 注释一个,另一个用@Component('documentQueueHelper') 注释。但是,现在您必须在每个要自动装配这些 bean 的地方提供 @Qualifier(<name>)

  2. 将它们排除在模块中,就像您在问题中所做的那样,然后使用 @Configuration 中的 @Bean 注释方法更改它们的名称。在第三个模块中使用时,您需要使用 @Qualifier 来自动装配正确的 bean。

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

【讨论】:

  • 谢谢,实际上由于某些限制,我只想在我的项目中进行更改。所以#3,是完美的解决方案,但不是我的情况。我再看看另外两个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
相关资源
最近更新 更多