Autowired与 Qualifer的使用区别备忘

               

原文链接:http://www.makaidong.com/%E5%8D%9A%E5%AE%A2%E5%9B%AD%E6%8E%A8%E8%8D%90/956.shtml

使用 @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, ImsTransactionManager]

原因:

比如配置文件中有二个 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

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

           

猜你喜欢

转载自blog.csdn.net/qq_44894420/article/details/89519472