Spring Autowiring @Qualifier example

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

Autowiring Example

See below example, it will autowired a “person” bean into customer’s person property.

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]]

转载于:https://www.cnblogs.com/ghgyj/p/4750257.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值