Spring自动装配(autowire)出错
报错如下:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘person‘ defined in class path resource [appContext.xml]: Unsatisfied dependency expressed through bean property ‘axe‘: : No qualifying bean of type [com.itheima.app.Axe] is defined: expected single matching bean but found 2: steelAxe,stoneAxe; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.itheima.app.Axe] is defined: expected single matching bean but found 2: steelAxe,stoneAxe
...
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.itheima.app.Axe] is defined: expected single matching bean but found 2: steelAxe,stoneAxe
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1126)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1292)
... 36 more
分析:
Caused by 这一行,提示我们未限定Axe类型(注:Axe是一个接口)的bean,发现两个实现bean都匹配Axe类型.
Spring的XML配置如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > <!-- <bean id="person" class="com.itheima.app.impl.Chinese" > <property name="axe" ref="steelAxe"></property> <property name="dog" ref="gunDog"></property> </bean> --> <bean id="person" class="com.itheima.app.impl.Chinese" autowire="byType"> <!-- 此处使用byType策略进行自动装配 --> </bean> <!-- 配置stellAxe Bean, 其实现类实现了Axe接口 --> <bean id="steelAxe" class="com.itheima.app.impl.SteelAxe" ></bean> <!-- 配置stoneAxe Bean, 其实现类也实现了Axe接口 --> <bean id="stoneAxe" class="com.itheima.app.impl.StoneAxe" ></bean> <bean id="gunDog" class="com.itheima.app.impl.GunDog" > <property name="name" value="wangwang"></property> </bean> </beans>
原因:
autowire="byType" 说明了是根据setter方法参数类型和bean的类型进行匹配.
<!-- 配置stellAxe Bean, 其实现类实现了Axe接口 --> <bean id="steelAxe" class="com.itheima.app.impl.SteelAxe" ></bean> <!-- 配置stoneAxe Bean, 其实现类也实现了Axe接口 --> <bean id="stoneAxe" class="com.itheima.app.impl.StoneAxe" ></bean>
看注释解释,因为容器中有两个类型为Axe的Bean,Spring无法确定应为person Bean注入那个Bean,所以程序抛出异常.
解决:
使用ref显式指定依赖,显式指定的依赖覆盖自动装配依赖
<bean id="person" class="com.itheima.app.impl.Chinese" autowire="byType">
<property name="axe" ref="steelAxe"></property>
</bean>