Spring Autowiring @Qualifier example
2015-08-22 14:44
405 查看
In Spring,
But, two similar beans “
When you run above example, it hits below exception :
To fix above problem, you need
In this case, bean “
@Qualifiermeans, 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
personproperty.
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 @Quanlifierto 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]]
相关文章推荐
- java8新增特性(一)---Lambda表达式
- Spring Auto-Wiring Beans with @Autowired annotation
- Spring中控制器方法返回字符串的一些细节
- 解决JAVA关于JTable列名无法显示问题
- 小白的Spring学习之路
- Java--泛型
- Java虚拟机内存分配策略
- 【Java 陷阱】SimpleDateFormat 时间格式化多线程异常
- 用Eclipse建spring mvc项目(图解)
- Myeclipse快捷键介绍
- struts2 jar包说明
- 从eclipse运行UiAutomator的方法,告别cmd
- How to run java and junit in command line
- java Map,Set,List的区别
- Javamail发送邮件的简单实例
- java中的equals和==
- java 对象和引用
- java 访问权限控制
- java中的hashcode方法
- Java 内存划分