首页 新闻 会员 周边

@Service在继承的时候,怎么用?

0
[已解决问题] 解决于 2020-04-08 11:12

interface A {
void say();
}
@Service
class A1 implements A {
void say(){System.out.println('A1');}
}
interface B extends A{
void say();
}
@Service
class B1 extends A1 implements B {
void say(){System.out.println('B1');}
}
报错:No unique bean of type [A] is defined: expected single matching bean but found 2: [B1, A1]

黑仔002的主页 黑仔002 | 菜鸟二级 | 园豆:204
提问于:2020-03-31 09:02
< >
分享
最佳答案
0

给每个service命名,例如

@Service("serviceA")
public class A

@Service("serviceB")
public class B

在注入的地方,同样要区分好名字,

    @Autowired
    @Qualifier("serviceA")
    A serviceA

默认情况下,spring会帮你以接口名小驼峰形式注入Bean,如果出现多个Bean实现了相同的类,那就要这样区分了。
实际业务上,应该尽量避免这种情况,以免引入不必要的麻烦,一般,你这个例子属于不合理的设计。

奖励园豆:5
。淑女范erり | 小虾三级 |园豆:961 | 2020-03-31 09:26

谢谢

黑仔002 | 园豆:204 (菜鸟二级) | 2020-04-08 11:12
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册