目录

@Qualifier

当您创建多个相同类型的bean并且只想使用属性连接其中一个bean时,可能会出现这种情况。 在这种情况下,您可以使用@Qualifier注释和@Autowired通过指定要连接的确切bean来消除混淆。 以下是显示@Qualifier注释使用的示例。

例子 (Example)

让我们有一个可用的Eclipse IDE,并按照以下步骤创建一个Spring应用程序 -

脚步 描述
1 创建一个名为SpringExample的项目,并在创建的项目中的src文件夹下创建一个包com.iowiki
2 使用Add External JARs选项添加所需的Spring库,如Spring Hello World Example章节中所述。
3com.iowiki包下创建Java类StudentProfileMainApp
4src文件夹下创建Beans配置文件Beans.xml
5 最后一步是创建所有Java文件和Bean配置文件的内容并运行应用程序,如下所述。

这是Student.java文件的内容 -

package com.iowiki;
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;
   }
}

这是Profile.java文件的内容

package com.iowiki;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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() );
   }
}

以下是MainApp.java文件的内容。

package com.iowiki;
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();
   }
}

请考虑以下配置文件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.iowiki.Profile"></bean>
   <!-- Definition for student1 bean -->
   <bean id = "student1" class = "com.iowiki.Student">
      <property name = "name" value = "Zara" />
      <property name = "age" value = "11"/>
   </bean>
   <!-- Definition for student2 bean -->
   <bean id = "student2" class = "com.iowiki.Student">
      <property name = "name" value = "Nuha" />
      <property name = "age" value = "2"/>
   </bean>
</beans>

完成源和bean配置文件的创建后,让我们运行应用程序。 如果您的应用程序一切正常,它将打印以下消息 -

Inside Profile constructor.
Age : 11
Name : Zara
↑回到顶部↑
WIKI教程 @2018