如果一個接口有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去識別不同的實現類

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章