Spring 同一介面注入多個bean實現

2022-05-23 11:42:09 字數 495 閱讀 1265

如果同乙個介面有多個bean實現類,spring在執行時會出現如下異常

required a single bean, but 2 were found:

marking one of the beans as @primary, updating the consumer to accept multiple beans, or using @qualifier to identify the bean that should be consumed

@primary的意思是在眾多相同的bean中,優先使用用@primary註解的bean.而@qualifier這個註解則指定某個bean有沒有資格進行注入。

@component

@primary

@autowired

@component

@qualifier("fjaoidfj")

@autowired

@qualifier("fjaoidfj")

在bean中注入同一介面多個實現類的bean

如果乙個介面存在多個實現類,而且多個實現類都被注入到spring容器中了,如果需要將它們都注入到同乙個bean中或者想要動態獲取某乙個bean的時候會發現一些問題,首先是如果只是單獨註冊乙個bean而且還是按照 bytype 註冊的,那麼還出現異常。這個時候如果一定要將多個bean都注入在乙個bea...

六 介面 Spring介面FactoryBean

factorybean是用來向容器中注入bean的介面。而beanfactory是從容器中取bean的介面。定義fish實體類 author zhangjianbing date 2020年9月23日 data public class fish public fish string name,in...

依賴注入例項3 介面注入

介面注入 也就是說將注入的 放在了介面裡,與建構函式和屬性注入在整體 結構上不同。用介面可以提高類的靈活性,將注入的 抽象出來放入介面裡這樣就不只是order類可以寫入資料庫了,其他的類如果也想寫入資料庫去實現介面即可。本篇 與前兩篇結構一樣,只是多了個注入用的介面 sqlserverdal acc...