一個接口多個實現類,controller層如何操作


spring中controller層會注入 接口,然后通過接口調用方法。

 如果一個接口對應一個實現類,這樣操作沒有問題,如果一個接口實現多個實現類(多態),這樣操作就會出現問題。

解決方法:一個接口多個實現類,需注入指定的實現類

例如:Interface 接口有兩個實現類 InterfaceImpl1 和 InterfaceImpl2

//實現類1
@Service
public class InterfaceImpl1 implements Interface {


//實現類2 @Service public class InterfaceImpl2implements Interface {

//業務類,controller @Autowired Interface private Interface interface; 按照上面的寫法,啟動服務時會報錯 解決方法 1.指明實現類的優先級,注入的時候使用優先級高的實現類 //實現類1 @Service @Primary //同一個接口的實現類,最多只能有一個添加該注解 public class InterfaceImpl1 implements Interface { 在controller中注入接口,默認使用的是Primary 標注的實現類的方法 2.通過 @Autowired 和 @Qualifier 配合注入 @Autowired @Qualifier(“interfaceImpl1”) Interface1 interface1; //正常啟動 3.使用@Resource注入,根據默認類名區分 @Resource(name = “interfaceImpl1”) Interface1 interface1; //正常啟動 4.使用@Resource注入,根據@Service指定的名稱區分 需要在實現類@Service后設置名稱: @Service(“s1”) public class InterfaceImpl1 implements Interface { @Resource(name = “s1”) Interface1 interface1; //正常啟動


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM