当我们编写一个接口时,可以有多个实现类,但是当使用字段注入时,对象的类型需要写成接口,所以当有多个实现类时就会抛出异常。在我看来解决的办法有两个:
1、使用set注入,在beans.xml中进行配置,例如:
<bean id="people" class="ccf.People"/> <-- People类实现了接口TestInterface->
<bean id="animal" class="ccf.Animal"/> <-- Animal类实现了接口TestInterface->
<bean id="say" class="ccf.Saying">
<property name="say" ref="animal"></property>
</bean>
这样的话在Saying类中就可以这样编写:
private TestInterface say;
public void setSay(TestInterface say) {
this.say = say;
}
2、使用字段注入时需要指明name属性。例如
@Resource(name="people")
private TestInterface say;
这样在beans.xml中就可以这样配置:
<bean id="people" class="ccf.People"/> <-- People类实现了接口TestInterface->
<bean id="animal" class="ccf.Animal"/> <-- Animal类实现了接口TestInterface->
<bean id="say" class="ccf.Saying"/>
此两种方式都可以解决接口注入时的问题。希望会对大家有所帮助。由于本人也是初学spring,理解的不是很好,还请高手指正!