[英]Id for Spring Bean/Repository
I have a repository B which I extend from another repository A. 我有一个存储库B,它是从另一个存储库A扩展的。
Repository A: 储存库A:
@Repository
public class RepositoryA implements Repository {
}
Repository B: 资料库B:
@Repository
public class RepositoryB extends RepositoryA implements RepositoryAux{
}
But when I try to inject the repository I am having the following error: 但是,当我尝试注入存储库时,出现以下错误:
No unique bean of type [Repository] is defined: expected single matching bean but found 2: [RepositoryA , RepositoryB]
没有定义[Repository]类型的唯一bean:需要单个匹配的bean,但是找到了2:[RepositoryA,RepositoryB]
I understand that I can solve it using the annotation @Qualifier. 我知道我可以使用@Qualifier注释解决它。 But, my question is:
但是,我的问题是:
it's right Overwrite the annotation @Repository in the child class ? 是的,在子类中覆盖注解@Repository吗?
Can I assign a new identifier to the child class? 我可以给子类分配一个新的标识符吗? Instead of using annotation @Qualifier, Something like @Id or @Name
而不是使用@Qualifier注释,而是@Id或@Name之类的东西
Thank's in advance 提前致谢
- it's right Overwrite the annotation @Repository in the child class ?
是的,在子类中覆盖注解@Repository吗?
There are a few things you should consider: 您应该考虑以下几点:
a. 一种。 If you intend to use
RepositoryA
as a repository, hen you need @Repository
on both. 如果打算将
RepositoryA
用作存储库,则两者都需要@Repository
。
b. b。 If you intent to use
RepositoryA
just to provide basic functionality so RepositoryB
(or other classes) can extend it, then make RepositoryA
abstract and annotate with NoRepositoryBean
如果您打算仅使用
RepositoryA
来提供基本功能,以便RepositoryB
(或其他类)可以对其进行扩展,则使RepositoryA
抽象并使用NoRepositoryBean
注释。
c. C。 Alternatively, you could use " composition over inheritance " principle.
或者,您可以使用“ 组成继承 ”原则。 In short you could inject
RepositoryA
into RepositoryB
and create facade or wrapper methods to access the methods on RepositoryB
instance. 简而言之,您可以将
RepositoryA
注入RepositoryB
并创建Facade或wrapper方法来访问RepositoryB
实例上的方法。
- Can I assign a new identifier to the child class?
我可以给子类分配一个新的标识符吗? Instead of using annotation @Qualifier, Something like @Id or @Name
而不是使用@Qualifier注释,而是@Id或@Name之类的东西
I think you mean @Named
from javax.inject.Named
which is basically equivalent to @Qualifier
我认为您的意思是
javax.inject.Named
中的@Named
,基本上等同于@Qualifier
I think you mean <bean id='...'
which in this case @Qualifier
is the way to do with annotations. 我认为您的意思是
<bean id='...'
,在这种情况下,@ @Qualifier
是使用批注的方式。 See spring's documentation 请参阅spring的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.