我有这对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 {
}
我正在尝试将它们注入(inject)一些 XXXServiceImpl 类(绝不会在同一个类中),如下所示:
@Autowired
private RequestTypeDao requestTypeDao;
因为它们不是同一种类型,我希望 Spring 根据从 corect 包中导入的类型进行注入(inject)(从来没有从同一个包中导入两个 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]
在错误处你可以看到类是不一样的。我已经阅读了有关 @Qualifier 注释的信息,但我知道这意味着更改 @Repository 注释中写入的名称。我还认为 @Resource 或 @Inject 不是我要找的。p>
我们不介意最后改名,但我们想知道是否可以通过Spring进行真正的按类型注入(inject)。这是两个具有相同名称和不同类类型的存储库,并且包被注入(inject)不同的和不同的类(从不相同)。
最佳答案
其实这是不可能的。无法将两个同名的 bean 注册到 spring 中。您必须使用 @Qualifier
否则 spring 无法在运行时处理您想要的 bean。
您可以了解更多here
@Autowired
@Qualifier("personA")
private Person person;
@Autowired
@Qualifier("personB")
private com.blabla.myOtherPackage.Person person;
关于java - 按类型 : two @Repository with same name 进行 Spring 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32265539/