DeliveryNinja DeliveryNinja - 8 months ago 43
Java Question

Spring @Autowired with 2 beans of the same type

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">
<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.

Answer Source

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)