现在的位置: 首页 > 综合 > 正文

@autowired与@qualifer的使用区别备忘

2012年06月16日 ⁄ 综合 ⁄ 共 900字 ⁄ 字号 评论关闭
使用@Autowired注释进行byType注入,如果需要byName(byName就是通过id去标识)注入,增加@Qualifier注释
@Qualifer如果没有的话, 报的错如下:
No unique bean of type [org.springframework.transaction.PlatformTransactionManager] is defined: expected single matching bean but found 2: [transactionManager, jmsTransactionManager]

原因:
比如配置文件中有二个bean.
<bean id="jmsTransactionManager"
        class="org.springframework.jms.connection.JmsTransactionManager">
        <property name="connectionFactory"
            ref="advancedConnectionFactory" />
    </bean>
<bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource">
            <ref bean="cpcDataSource" />
        </property>
    </bean>
表面看起来是不同类型的类,但是由于在*Service里面注入的属性类型是PlatformTransactionManager.由于上面的二个bean都实现了这个接

口.这样@autowired时,由于是bytype注入,就不能识别.此时就需要再加上@qualifer通过id去识别.

而如果没有使用@Service的话,报错如下:
No unique bean of type ..... expected at least 1 matching bean

注意,这与上面的提示信息区别.


抱歉!评论已关闭.