Spring Autowiring仅适用于Interface [英] Spring Autowiring only works with Interface
问题描述
我对spring框架很新,遇到了以下问题。
I am quite new to spring framework and came across the following issue.
我有一个接口 ClassA
,由分类 ClassA1
和 ClassA2
实现。
I have an interface ClassA
, which is implemented by classed ClassA1
and ClassA2
.
我将以下bean定义添加到 applicationContext.xml
I have the following bean definition added to applicationContext.xml
<bean id="class1" class="com.abc.ClassA1" />
<bean id="class2" class="com.abc.ClassA2" />
我想将两个实现类自动装配如下。
I would like to Autowire both the implementation classes as below.
@Autowired
private ClassA1 classA1;
@Autowired
private ClassA2 classA2;
上面的代码抛出错误
无法自动写入字段:com.abc.ClassA1 com.abc.SomeClass.classA1;嵌套异常是
org.springframework.beans.factory.NoSuchBeanDefinitionException:
没有匹配的
类型的bean [com.abc.ClassA1]
Could not autowrite to field: com.abc.ClassA1 com.abc.SomeClass.classA1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.abc.ClassA1]
但是,如果我将自动装配更改为接口,如下所示:
But, if I change the autowiring to interface as below:
@Autowired
ClassA classA1;
然后ClassA1自动连接到变量。我无法知道如何将变量自动装配到ClassA2。
Then ClassA1 is autowired to the variable. I am clueless on how can I autowire a variable to ClassA2.
推荐答案
我尝试了多种方法来解决这个问题,但我得到了它按以下方式工作。
I tried multiple ways to fix this problem, but I got it working the following way.
@Autowired
private ClassA classA1;
@Autowired
private ClassA classA2;
在应用程序上下文中,我将bean定义如下:
In the application context, I defined the bean as below:
<bean id="classA1" class="com.abc.ClassA1" autowire="byName" />
<bean id="classA2" class="com.abc.ClassA2" autowire="byName" />
这篇关于Spring Autowiring仅适用于Interface的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!