开发者

Spring @Autowired with 2 beans of the same type

开发者 https://www.devze.com 2023-01-20 07:11 出处:网络
I have the following defined. @Autowired DaoType1<object1> someDao; @Autowired DaoType1<object1> someListDao;

I have the following defined.

@Autowired
DaoType1<object1> someDao;

@Autowired
DaoType1<object1> someListDao;

and in my bean definitions I have two beans of the same type

<bean id="someDao" class="com.example.DaoType1" />
<bean id="someListDao" class="com.example.DaoType1" />

The second bean is imported from another xml file if that makes a difference. They have different properties being set as well. Why is spring not throwing an error because 2 beans of the same type have been defined. Does it use the variable names since they match the bean ids. The dao's are different and the functionality works as expected if I had used @Qualifiers for the two different beans.

Here is a more concise version. I've left out other beans since I they are not relevant.

applicationContext.xml

<import resource="classpath:dm-services-crud.xml"/>
<bean id="ruleListCrudService" class="com.idna.dm.service.crud.impl.RuleCrudServiceImpl"> 
    开发者_如何学Go<property name="crudDao" ref="ruleListCrudDao" />
</bean>

dm-services-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 is not present in any of my xml files at all.


This appears to be expected behaviour. The documentation says:

byName

Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master, and uses it to set the property.

I guess this means you have specified default-autowire="byName" in your applicationContext.xml.

However, refactoring may affect this in an unpredictable way. That's why (I think) it is advisable to switch to autowiring by type, and disambiguate the beans by the use of

  • @Qualifier (as you noted)
  • @Resource rather than @Autowired (as skaffman noted)


The @Autowired annotation behaves slightly differently to the "autowire by type" specification on xml based bean definitions.

When using annotations you're not technically doing an auto wire... you're setting the value based on the annotation. The autowire annotation has the same function as the xml property element.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号