如果一个接口有2个不同的实现, 那么怎么来一个指定的实现

就目前的理解来说,两个不同实现的区分可以通过两种途径来进行区分:
1、是比较老的方法,声明bean的时候指定不同的名字,注入的时候直接使用
2、采用注解之间的不同点进行注入,这里涉及到两个注解,@Autowired和@Resource

  • @Autowired根据类型来进行自动注入,因为是类型相同的两个实现,需要配合@Qualifier才能达到目的
  • @Resource根据名字来进行自动注入

下面是测试的代码:

  • 接口
public interface TestService {
}
  • 两个实现类
@Service
public class TestImpl1 implements TestService {
}
@Service
public class TestImpl2 implements TestService {
}
  • 服务的使用者
@Controller
public class TestController {
	@Autowired
	TestService testService;
}

如果单纯这样指定是会出现下面的错误的:

No qualifying bean of type [TestService] is defined: 
expected single matching bean but found 2: TestImpl1,TestImpl2

两种解决方式:

  • 依然使用@Autowired注解版本
@Service("TestImpl1")
public class TestImpl1 implements TestService {
}
@Service("TestImpl2")
public class TestImpl2 implements TestService {
}
@Controller
public class TestController {
	@Autowired
	@Qualifier("TestImpl1")
	TestService testService;
}
  • 使用@Resource版本
@Controller
public class TestController {
	@Resource(name = "TestImpl1")
	TestService testService;
}

其实两种方式都是通过别名的方式让spring去识别不同的实现类

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值