1. 程式人生 > 其它 >一個介面多個實現類,controller層如何操作

一個介面多個實現類,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; //正常啟動

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

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

複製程式碼
例如: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; //正常啟動