關於expected single matching bean but found 2的問題
問題:
org.springframework.context.support.AbstractApplicationContext refresh
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userLoginServlet' defined in class path resource [spring.xml]: Unsatisfied dependency expressed through bean property 'userDao'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'cn.tedu.spring.UserDao' available: expected single matching bean but found 2: userDao,subUserDao
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userLoginServlet' defined in class path resource [spring.xml]: Unsatisfied dependency expressed through bean property 'userDao'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'cn.tedu.spring.UserDao' available: expected single matching bean but found 2: userDao,subUserDao
***——>Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'cn.tedu.spring.UserDao' available: expected single matching bean but found 2: userDao,subUserDao
分析:使用了根據類型(byType
)的自動裝配方式,這種自動裝配要求最多只有1個匹配類型的對象,但是,在Spring容器中卻出現了2個這樣的對象,Spring就不知道應該裝配哪一個了,就會出現錯誤!
解決方案:使得Spring只管理其中1個類型的對象,或者,使用byName
方式來裝配。
異常:NoUniqueBeanDefinitionException:不唯一的Bean匹配異常