spring容器中能擁有兩個同種類型的bean嗎?我有兩個dao類同時實現一個接口,這兩個接口注入時報了異常如下。
- org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.xxx.xxx.xxx.integration.dao.IDAO] is defined: expected single matching bean but found 2: [aDAOImpl, bDAOImpl]
解決方法:
兩個類實現同一個接口,在一個實現類加上@Component("aDAOImpl"),一個加上@Component("bDAOImpl"),在引用的時候加上@Resource(name="aDAOImpl")或者@Resource(name="bDAOImpl"),就會指定用哪個實現類,不加resource注解就會出現上面那個錯誤。
但需特別強調的是,如果有其它的service用到實現類時沒用@Resource,要把所有使用到實現類的注解由@Autowired改為@Resource。