java - 运行spring boot项目时bean名称冲突

标签 java spring spring-boot exception

背景:我正在一个名为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 中使用它

我得到的异常(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]

最佳答案

我想到了三个答案:

  1. com.x.library.utils.QueueHelper 取一个不同的名字和 com.x.document.utils.QueueHelper通过 @Component注解。默认情况下,Spring 将使用简单的类名来命名 bean。你可以用 @Component('libraryQueueHelper') 注释一个另一个是@Component('documentQueueHelper') .但是,现在您必须提供 @Qualifier(<name>)在您 Autowiring 这些 bean 的每个地方。

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

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

关于java - 运行spring boot项目时bean名称冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304437/

相关文章:

java - JAX-WS 客户端基本身份验证

java - hbm2ddl 更新在 Spring Boot 中给出错误

java - Spring Boot JPA - ManyToOne关系导致额外的sql

spring-security - Thymeleaf + Spring Security 表达语言

java - 精简模式下的 MapView 导致 RecyclerView 无法正确滚动

java - 打开连接时出现 UCanAccess 异常 - 引用的列上不存在 UNIQUE 约束

java - spring.io 中的 Spring Cloud 配置示例不起作用

java - 具有太多类的命令模式

java - 将一个数字添加到固定的最大数字

java - spring-data-jpa 和 spring-boot-starter-data-jpa 的区别