Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

java - Spring Autowiring only works with Interface

I am quite new to spring framework and came across the following issue.

I have an interface ClassA, which is implemented by classed ClassA1 and ClassA2.

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;

The above code is throwing error as

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;

Then ClassA1 is autowired to the variable. I am clueless on how can I autowire a variable to ClassA2.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For some reason your classes are proxied by Spring. There many reasons why this can happen. For example if you use JPA, or AOP the original class is proxied.

If a class implements an interface, proxy means Dynamic Proxy. So basically a new class is created in runtime that implements the interfaces but does not inherit from the original class. Therefore the autowiring to the original class doesn't work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...