[英]Spring @Autowired with 2 beans of the same type
我有以下定義。
@Autowired
DaoType1<object1> someDao;
@Autowired
DaoType1<object1> someListDao;
在我的bean定義中,我有兩個相同類型的bean
<bean id="someDao" class="com.example.DaoType1" />
<bean id="someListDao" class="com.example.DaoType1" />
第二個bean是從另一個xml文件導入的,如果這有所不同的話。 它們也有不同的屬性。 為什么spring沒有拋出錯誤,因為已經定義了2個相同類型的bean。 它是否使用變量名稱,因為它們匹配bean ID。 如果我將@Qualifiers用於兩個不同的bean,那么dao是不同的,並且功能按預期工作。
這是一個更簡潔的版本。 因為我沒有相關性,所以我遺漏了其他豆子。
applicationContext.xml中
<import resource="classpath:dm-services-crud.xml"/>
<bean id="ruleListCrudService" class="com.idna.dm.service.crud.impl.RuleCrudServiceImpl">
<property name="crudDao" ref="ruleListCrudDao" />
</bean>
DM-服務,crud.xml
<bean id="ruleCrudService" class="com.idna.dm.service.crud.impl.RuleCrudServiceImpl">
<property name="crudDao" ref="ruleCrudDao" />
<property name="ruleNetworkOfNodesCrudService" ref="ruleNetworkOfNodesCrudService" />
<property name="elementMappingsCrudService" ref="elementMappingsCrudService" />
<property name="ruleCrudDao" ref="newRuleCrudDao"/>
</bean>
default-autowire根本不存在於我的任何xml文件中。
這似乎是預期的行為。 文件說:
按名字
按屬性名稱自動裝配。 Spring查找與需要自動裝配的屬性同名的bean。 例如,如果bean定義按名稱設置為autowire,並且它包含master屬性(即,它具有setMaster(..)方法),則Spring會查找名為master的bean定義,並使用它來設置屬性。
我想這意味着你已經在applicationContext.xml中指定了default-autowire="byName"
。
但是,重構可能會以不可預測的方式影響這一點。 這就是為什么(我認為)建議按類型切換到自動裝配,並通過使用來消除bean的歧義
@Qualifier
(正如你所說) @Resource
而不是@Autowired
(正如skaffman所說) @Autowired
注釋與基於xml的bean定義的“按類型的autowire”規范略有不同。
使用注釋時,您從技術上講不是自動連線...您正在根據注釋設置值。 autowire注釋與xml屬性元素具有相同的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.