@Qualifier注解

      如果在xml中定义了一种类型的多个bean,同时在java注解中又想把其中一个bean对象作为属性,那么此时可以使用@Qualifier加@Autowired来达到这一目的,若不加@Qualifier这个注解,在运行时会出现“ No qualifying bean of type [com.tutorialspoint.Student] is defined: expected single matching bean but found 2: student1,student2”这个异常

具体怎么使用,直接看例子程序:

Step Description
1 创建SpringExample的项目,并创建一个net.csdn.john的包
2 将项目需要的spring库文件加入到项目(右键项目,进入build path config,。。。)
3 net.csdn.john包下创建以下几个java类: Student, Profile and MainApp
4 在src目录下创建Beans.xml描述文件
   

1.下面是 Student.java 文件内容:

package net.csdn.john;

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

2.以下是Profile.java文件内容:

package net.csdn.john;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Profile {
   @Autowired
   @Qualifier("student1")   //注意这个地方,使用的是student1这个bean
   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() );
   }
}

3.下面是MainApp.java文件内容:
package net.csdn.john;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

4.最后是Beans.xml文件内容
xml version="1.0" encoding="UTF-8"?>

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

   

   
    id="profile" class="com.tutorialspoint.Profile">
   

   
    id="student1" class="com.tutorialspoint.Student">
       name="name"  value="ken" />
       name="age"  value="11"/>
   

   
    id="student2" class="com.tutorialspoint.Student">
       name="name"  value="john" />
       name="age"  value="1"/>
   



运行上面的程序,会打印以下信息:
Inside Profile constructor.
Age : 11
Name : ken

上面信息就是student1这个bean的信息



你可能感兴趣的:(java)