Spring @Qualifier 注释

可能会有这样一种情况,当你创建多个具有相同类型的 bean 时,并且想要用一个属性只为它们其中的一个进行装配。

在这种情况下,你可以使用 @Qualifier 注释和 @Autowired 注释通过指定哪一个真正的 bean 将会被装配来消除混乱。

下面显示的是使用 @Qualifier 注释的一个示例。

  • 新建Spring项目

  • 创建 Java 类 Student,Profile 和 MainApp

这里是 Student.java 文件的内容:

package hello;
//import org.springframework.beans.factory.annotation.Autowired;

public class Student {
    private int age;
    String name;
    public void setAge(int age){
        this.age = age;
    }
    public int getAge(){
        return age;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
}

这里是 Profile.java 文件的内容:

package hello;
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 hello;
//import org.springframework.context.support.AbstractApplicationContext;
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.printName();
        profile.printAge();
    }
}

配置文件 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="hello.Profile" >
    </bean>

    <!-- Definition for student1 bean -->
    <bean id="student1" class="hello.Student">
        <property name="name" value="番茄"/>
        <property name="age" value="11"/>
    </bean>

    <!-- Definition for student2 bean -->
    <bean id="student2" class="hello.Student">
        <property name="name" value="西瓜"/>
        <property name="age" value="22"/>
    </bean>

</beans>

运行如下

Inside Profile constructor
name: 番茄
age: 11

注:在文件 Profile.java 中,使用 @Qualifier("student1")指定student1这个bean被装配。

由运行结果也可以看出。

每天学习一点点,每天进步一点点。

原文地址:https://www.cnblogs.com/youcoding/p/12790147.html