Spring @Autowired有2个相同类型的bean

Del*_*nja 3 java spring

我有以下定义.

@Autowired
DaoType1<object1> someDao;

@Autowired
DaoType1<object1> someListDao;
Run Code Online (Sandbox Code Playgroud)

在我的bean定义中,我有两个相同类型的bean

<bean id="someDao" class="com.example.DaoType1" />
<bean id="someListDao" class="com.example.DaoType1" />
Run Code Online (Sandbox Code Playgroud)

第二个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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

default-autowire根本不存在于我的任何xml文件中.

Boz*_*zho 8

这似乎是预期的行为.该文件说:

按名字

按属性名称自动装配.Spring查找与需要自动装配的属性同名的bean.例如,如果bean定义按名称设置为autowire,并且它包含master属性(即,它具有setMaster(..)方法),则Spring会查找名为master的bean定义,并使用它来设置属性.

我想这意味着你已经default-autowire="byName"在applicationContext.xml中指定了.

但是,重构可能会以不可预测的方式影响这一点.这就是为什么(我认为)建议按类型切换到自动装配,并通过使用来消除bean的歧义

  • @Qualifier (如你所说)
  • @Resource而不是@Autowired(正如斯卡弗曼所说)