背景:我正在一个名为com.x.myproject
的项目中工作。我依赖于另外两个包 com.x.document
和 com.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
中使用它
我得到的异常(exception)是
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]
最佳答案
我想到了三个答案:
给
com.x.library.utils.QueueHelper
取一个不同的名字和com.x.document.utils.QueueHelper
通过@Component
注解。默认情况下,Spring 将使用简单的类名来命名 bean。你可以用@Component('libraryQueueHelper')
注释一个另一个是@Component('documentQueueHelper')
.但是,现在您必须提供@Qualifier(<name>)
在您 Autowiring 这些 bean 的每个地方。将它们排除在您的模块中,就像您在问题中所做的那样,然后使用
@Bean
更改它们的名称@Configuration
中的注释方法.在第三个模块中使用时,您需要使用@Qualifier
Autowiring 正确的 bean。重命名类。这是这种情况下的最佳解决方案,但既然你问了这个问题,我想它是不可行的。
关于java - 运行spring boot项目时bean名称冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304437/