Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowiring Spring superclass

Why does Spring automatically choose the superclass types during autowiring?

For instance, if I have

@Component
public class Foo {}

@Component
public class Bar extends Foo {}

and someone autowires

@Autowired
private Foo foo;

How come Spring always chooses the supertype Foo? Shouldn't this be an "ambiguous" mapping (and cause Spring to throw an error)?

Don't you technically have two Foo candidates? (e.g., Bar gets automatically picked when @Component is removed from Foo...)

like image 223
ManRow Avatar asked May 22 '13 04:05

ManRow


1 Answers

That might be because the autowiring is done by name, not type. If I setup my bean using xml like this:

<bean id="foo1" class="Foo"/>
<bean id="foo2" class="Bar"/>

And attempt to autowire by type:

@Autowired private Foo aFoo;

I get

org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [Foo]
like image 166
gerrytan Avatar answered Sep 19 '22 13:09

gerrytan