1. 程式人生 > 其它 >Spring深入淺出(十),註解,@Qualifier

Spring深入淺出(十),註解,@Qualifier

可能會有這樣一種情況,當你建立多個具有相同型別的 bean 時,並且想要用一個屬性只為它們其中的一個進行裝配,在這種情況下,你可以使用@Qualifier註釋和@Autowired註釋通過指定哪一個真正的 bean 將會被裝配來消除混亂。

一、建立實體Bean

package com.clzhang.spring.demo;

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

二、建立業務邏輯層

package com.clzhang.spring.demo;

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

三、建立主程式

package com.clzhang.spring.demo;

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

四、配置檔案如下

<?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.clzhang.spring.demo.Profile">
   </bean>

   <!-- Definition for student1 bean -->
   <bean id="student1" class="com.clzhang.spring.demo.Student">
      <property name="name"  value="Zara" />
      <property name="age"  value="11"/>
   </bean>

   <!-- Definition for student2 bean -->
   <bean id="student2" class="com.clzhang.spring.demo.Student">
      <property name="name"  value="Nuha" />
      <property name="age"  value="2"/>
   </bean>

</beans>

五、執行

Inside Profile constructor.
Age : 2
Name : Nuha

本文參考:

https://www.w3cschool.cn/wkspring/knqr1mm2.html