如果⼀个接⼝有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去识别不同的实现类

猜你喜欢

转载自blog.csdn.net/m0_37664906/article/details/79894335