使用 @Qualifier 注释和 @Autowired 注释通过指定哪一个真正的 bean 将会被装配来消除混乱...

1、当你创建多个具有相同类型的 bean 时,并且想要用一个属性只为它们其中的某一个进行装配,在这种情况下,你可以使用 @Qualifier 注释和 @Autowired 注释来精确配置。

2、示例

java

public 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;
   }
}
public 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() );
   }
}
public 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

<?xml version="1.0" encoding="UTF-8"?>
<beans>
   <context:annotation-config/>
<bean id="profile" class="com.tutorialspoint.Profile"></bean>
<bean id="student1" class="com.tutorialspoint.Student"> <property name="name" value="Zara" /> <property name="age" value="11"/> </bean>

<bean id="student2" class="com.tutorialspoint.Student"> <property name="name" value="Nuha" /> <property name="age" value="2"/> </bean>
</beans>

打印输出

Inside Profile constructor.
Age : 11
Name : Zara

  

转载于:https://www.cnblogs.com/wangdapeng/p/5053585.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值