Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Autowired by constructor looks for beans by type. How to inject a bean by name to a constructor using autowired annotation

Tags:

@Autowired by constructor looks for beans by type. How to inject a bean by name to a constructor using autowired annotation? I have 2 beans of same type but I need to inject it to constructor of another same class based on the bean name. How do I do it?

XML:

 <bean id="A" class="com.Check"/>  <bean id="B" class="com.Check"/> 

Java:

Class C {     private Check check;     @Autowired    public C(Check check){        this.check = check    }    } 

When I do this I get an exception telling me that I have 2 beans of same type check but it requires there to be just one bean of that type. How can I inject the bean with id="B" into this class C through constructor injection?

In my applicationContext.xml I have mentioned autowire="byType". I need to autowire byName only in this particular class rest all it needs to be autowired by Type only

like image 636
user2972319 Avatar asked Nov 09 '13 16:11

user2972319


People also ask

Does Spring @autowired inject beans by name 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.

Can we use @autowired on constructor?

You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file.

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.

What @autowired annotation uses for bean injection?

Enabling @Autowired annotation By declaring beans, you provide metadata to the Spring Container to return the required dependency object at runtime. This is called Spring Bean Autowiring. In java based configuration, all the bean methods are defined in the class with @configuration annotation.


1 Answers

You should use @Qualifier annotation with your target bean id for constructor parameter.

<bean id="A" class="com.Check"/> <bean id="B" class="com.Check"/>  Class C {     private Check check;     @Autowired    public C(@Qualifier("A") Check check){ //<-- here you should provide your target bean id       this.check = check    } } 
like image 172
nndru Avatar answered Jan 26 '23 01:01

nndru