Saturday, August 12, 2017

Qualifier - spring beans

In Spring, @Qualifier means, which bean is qualify to autowired on a field. 

package com.mkyong.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Customer {

@Autowired
private Person person;
//...
}

But, two similar beans “com.mkyong.common.Person” are declared in bean configuration file. Will Spring know which person bean should autowired?

(beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd")

(bean
class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/)

(bean id="customer" class="com.mkyong.common.Customer" /)

(bean id="personA" class="com.mkyong.common.Person" )
(property name="name" value="mkyongA" /)
(/bean)

(bean id="personB" class="com.mkyong.common.Person" )
(property name="name" value="mkyongB" /)
(/bean)

(/beans)

When you run above example, it hits below exception :

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.mkyong.common.Person] is defined:
expected single matching bean but found 2: [personA, personB]

@Qualifier Example
To fix above problem, you need @Quanlifier to tell Spring about which bean should autowired.

package com.mkyong.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Customer {

@Autowired
@Qualifier("personA")
private Person person;
//...
}
In this case, bean “personA” is autowired.

Customer [person=Person [name=mkyongA]]

No comments:

Post a Comment

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...