Spring基于注解的配置之@Qualified

学习地址:https://www.w3cschool.cn/wkspring/knqr1mm2.html

当创建具有多个相同类型的bean时,并且想要用一个属性只为他们其中一个进行装配,在这种情况下,可以使用@Qualified注释和@Autowired注释通过指定哪一个真正的bean。看文字可能难以理解,看看实例就明白了:

Student.java :实体类

package com.lee.Qualifier;

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

Profile.java:打印类

package com.lee.Qualifier;

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

public class Profile {
    
    @Autowired
    @Qualifier("student2")
    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.lee.Qualifier;

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

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans4.xml");
        Profile pf = (Profile) context.getBean("profile");
        pf.printAge();
        pf.printName();
    }

}

Beans4.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 />

    <bean id="student1" class="com.lee.Qualifier.Student">
        <property name="name" value="lile"></property>
        <property name="age" value="18"></property>
    </bean>    
    
    <bean id="student2" class="com.lee.Qualifier.Student">
        <property name="name" value="hrx"></property>
        <property name="age" value="20"></property>
    </bean>    
    
    
    <bean id="profile" class="com.lee.Qualifier.Profile"></bean>

</beans>

这里@Qualified指定Student1就打印XML里为Student1的,指定Student2的就打印Student2的;

若不指定,则会报错:

猜你喜欢

转载自www.cnblogs.com/lemon-le/p/9317189.html