Spring 按类型注入:两个同名的@Repository

Spring injection by type: two @Repository with same name

我有这对daos:

package com.company.project.model.requests.type;

@Repository("requestTypeDao")
public class RequestTypeDaoHibernate extends AbstractReadDao implements RequestTypeDao {

}

package com.company.project.model.support.type;

@Repository("requestTypeDao")
public class RequestTypeDaoHibernate extends AbstractReadDao implements RequestTypeDao {

}

我正在尝试将它们注入某些 XXXServiceImpl classes(永远不会在同一个 class 中),如下所示:

@Autowired
private RequestTypeDao requestTypeDao;

因为它们不是同一种类型,我希望Spring根据从 corect 包中导入的类型进行注入(从来没有从同一个包中导入两个 RequestTypeDao),但它显示错误:

Annotation-specified bean name 'requestTypeDao' for bean class [com.company.project.model.support.type.RequestTypeDaoHibernate] conflicts with existing, non-compatible bean definition of same name and class [com.company.project.model.requests.type.RequestTypeDaoHibernate]

报错处可以看到class不一样。我已经阅读了有关 @Qualifier 注释的信息,但我知道这意味着更改 @Repository 注释中写入的名称。我也认为@Resource 或@Inject 不是我要找的。

我们最终不介意改名,但想知道是否可以通过Spring实现真正的按类型注入。这是两个具有相同名称和不同 class 类型和包的存储库,它们被注入不同的 classes(从不相同)。

其实这是不可能的。无法将两个相同命名的 bean 注册到 spring。你必须使用 @Qualifier 否则 spring 无法在运行时处理你想要的哪个 bean。

你可以了解更多here

@Autowired
@Qualifier("personA")
private Person person;



@Autowired
@Qualifier("personB")
private com.blabla.myOtherPackage.Person person;