Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowiring spring bean by name using annotation

In Springs latest version, we can autowire a bean using annotation as @Autowired. This will autowire the bean using its type(or constructor, if applied on it). Is there any way I can use the @Autowired annotation based on the bean name which we were doing without annotation in Spring's XML file as autowire="byName"?

like image 225
Anand Avatar asked Aug 06 '12 15:08

Anand


People also ask

How do you Autowire beans with names?

Autowiring by Name. Spring uses the bean's name as a default qualifier value. It will inspect the container and look for a bean with the exact name as the property to autowire it.

Can we do Autowired byName?

Autowiring Modes byName : The byName mode injects the object dependency according to name of the bean. In such a case, the property and bean name should be the same. It internally calls the setter method. byType : The byType mode injects the object dependency according to type.

Does spring @autowired inject beans byName or by type?

if Spring encounters multiple beans with same type it checks field name. if it finds a bean with the name of the target field, it injects that bean into the field.

How do you auto inject a field into a bean by its name?

D. By using the @Autowired annotation and naming the field with the bean name.


1 Answers

You can use:

@Autowired @Qualifier("beanname") 

According to the @Qualifier javadoc

This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring

like image 117
Biju Kunjummen Avatar answered Sep 20 '22 14:09

Biju Kunjummen