Spring自动装配@Qualifier示例

在Spring中,@ Qualifier表示哪个bean有资格在字段上自动装配。 请参阅以下场景:

自动接线示例

参见下面的示例,它将自动将“ person” bean连线到客户的person属性中。

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;
	//...
}

但是,在bean配置文件中声明了两个类似的bean“ com.mkyong.common.Person ”。 Spring会知道应该自动连接哪个人的bean?

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

在上面的示例中运行时,它会在下面的异常中命中:

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示例

要解决上述问题,您需要@Quanlifier告诉Spring应该自动装配哪个bean。

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;
	//...
}

在这种情况下,bean“ personA”是自动装配的。

Customer [person=Person [name=mkyongA]]

下载源代码

下载它– Spring-AutoWiring-Qualifier-Example.zip (6 KB)

参考

  1. Spring @Autowired示例

翻译自: https://mkyong.com/spring/spring-autowiring-qualifier-example/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值