@Qualifier注解

来源:互联网 发布:c语言实现socket编程 编辑:程序博客网 时间:2024/05/23 23:48

      如果在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”这个异常

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

StepDescription1创建SpringExample的项目,并创建一个net.csdn.john的包2将项目需要的spring库文件加入到项目(右键项目,进入build path config,。。。)3在net.csdn.john包下创建以下几个java类: Student,Profile and MainApp4在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"?><beans 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">   <context:annotation-config/>   <!-- Definition for profile bean -->   <bean id="profile" class="com.tutorialspoint.Profile">   </bean>   <!-- Definition for student1 bean -->   <bean id="student1" class="com.tutorialspoint.Student">      <property name="name"  value="ken" />      <property name="age"  value="11"/>   </bean>   <!-- Definition for student2 bean -->   <bean id="student2" class="com.tutorialspoint.Student">      <property name="name"  value="john" />      <property name="age"  value="1"/>   </bean></beans>运行上面的程序,会打印以下信息:
Inside Profile constructor.Age : 11Name : ken上面信息就是student1这个bean的信息



0 0
原创粉丝点击