Autowiring Spring superclass

Why does Spring automatically select superclass types during auto-preparation?

For example, if I have

@Component public class Foo {} @Component public class Bar extends Foo {} 

and someone autwires

 @Autowired private Foo foo; 

Why does Spring always choose the Foo supertype? Shouldn't this be an " ambiguous " mapping (and cause a Spring error)?

You have no technical candidates two Foo ? (e.g. Bar is automatically selected when @Component is removed from Foo ...)

+6
source share
3 answers

Perhaps this is due to the fact that auto-installation is performed by name, and not by type. If I configure my bean using xml as follows:

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

And try to perform auto-assertion by type:

 @Autowired private Foo aFoo; 

I get

 org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [Foo] 
+9
source

Autowiring can work with the type name and bean, depending on how you configured it.

In this case, since there are two beans of type Foo , an instance of Foo can be selected because it matches the variable name Foo .

What happens if you rename Foo to another?

+3
source

If there are two beans of the same type, then spring tries to resolve the dependency by the name of the variable you specify. If the name does not match any of the bean names, it causes an error. But if it finds a bean name that matches the name of the variable name you specified, it will enter a bean. Thus, when introducing dependencies, spring takes into account both type and name.

+3
source

Source: https://habr.com/ru/post/945536/


All Articles