spring|Spring 基于注解(annotation)的配置之@Qualifier注解


使用@Qualifier可以分别为同样类型的Bean分别注入不同的依赖值 。 看个例子:
Student.java:
package com.sappublic class Student { private Integer age private String name public void setAge(Integer age) { this.age = age }public Integer getAge() { return age } public void setName(String name) { this.name = name }public String getName() { return name }}
Profile:
package com.sapimport org.springframework.beans.factory.annotation.Autowiredimport org.springframework.beans.factory.annotation.Qualifierpublic class Profile { @Autowired @Qualifier("student1") private Student student public Profile(){ System.out.println("Inside Profile constructor." ) } public void printAge() { System.out.println("Age : " + student.getAge() ) } public void printName() { System.out.println("Name : " + student.getName() ) }}
Main.app:

package com.sapimport org.springframework.context.ApplicationContextimport org.springframework.context.support.ClassPathXmlApplicationContextpublic class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml") Profile profile = (Profile) context.getBean("profile") profile.printAge() profile.printName() }}
Beans.xml:
&ltbeans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt &ltcontext:annotation-config/&gt&ltbean id="profile" class="com.sap.Profile"&gt bean&gt
&ltbean id="student1" class="com.sap.Student"&gt &ltproperty name="name" value="http://news.hoteastday.com/a/Zara" /&gt &ltproperty name="age" value="http://news.hoteastday.com/a/11"/&gt bean&gt&ltbean id="student2" class="com.sap.Student"&gt &ltproperty name="name" value="http://news.hoteastday.com/a/Nuha" /&gt &ltproperty name="age" value="http://news.hoteastday.com/a/2"/&gt bean&gtbeans&gt 输出:
如果把profile类里的id改成student2:
spring|Spring 基于注解(annotation)的配置之@Qualifier注解
本文插图
【spring|Spring 基于注解(annotation)的配置之@Qualifier注解】

输出:
spring|Spring 基于注解(annotation)的配置之@Qualifier注解
本文插图

声明:转载此文是出于传递更多信息之目的 。 若有来源标注错误或侵犯了您的合法权益 , 请作者持权属证明与本网联系 , 我们将及时更正、删除 , 谢谢 。邮箱地址:newmedia@xxcb.cn


    推荐阅读