Spring 註解注入—@Qualifier 註釋

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

 

1.這裏是 Student.java 文件的內容:

 1 package com.spring.chapter7;
 2 
 3 public class Student {
 4     public String getName() {
 5         return name;
 6     }
 7     public void setName(String name) {
 8         this.name = name;
 9     }
10     public int getAge() {
11         return age;
12     }
13     public void setAge(int age) {
14         this.age = age;
15     }
16     private String name;
17     private int age;
18     
19 
20 
21 }

2.這裏是 Profile.java 文件的內容:

 1 package com.spring.chapter7;
 2 
 3 import java.util.List;
 4 import java.util.Set;
 5 
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.beans.factory.annotation.Qualifier;
 8 import org.springframework.beans.factory.annotation.Required;
 9 
10 
11 
12 public class Profile {
13     
14     @Autowired
15     @Qualifier("Student")    //這裏的值就是bean的id,當我們改變此值跟隨我們指定的bean進行注入
16     private Student student;
17     
18     public void printName() {
19         System.out.println("age:"+student.getName());
20     }    
21     
22     public void printAge() {
23         System.out.println("name:"+student.getAge());
24     }
25 
26     public Profile() {
27         System.out.println("--------構造方法------------");
28     }
29 }

3.下面是 MainApp.java 文件的內容:

 1 package com.spring.chapter7;
 2 
 3 
 4 import java.util.List;
 5 
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.context.support.AbstractApplicationContext;
 8 import org.springframework.context.support.ClassPathXmlApplicationContext;
 9 
10 public class Main {
11     /**
12      * Spring @Qualifier  註解注入
13      * author:
14      * mail:[email protected]
15      * 時間:
16      */
17 
18     public static void main(String[] args) {
19         ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring_xml/spring.xml");
20         Profile profile=(Profile)applicationContext.getBean("Profile");
21         profile.printName();
22         profile.printAge();
23         
24         
25     }
26 
27 }

4.下面配置文件 spring.xml 的示例:

 1     <!-- @Qualifier 註解 -->
 2     <bean id="Profile" class="com.spring.chapter7.Profile">
 3     </bean>
 4     <bean id="Student" class="com.spring.chapter7.Student">
 5         <property name="name" value="張三"></property>
 6         <property name="age" value="23"></property>
 7     </bean>
 8     
 9     <bean id="Student2" class="com.spring.chapter7.Student">
10         <property name="name" value="李四"></property>
11         <property name="age" value="22"></property>
12     </bean>

運行結果:

--------構造方法------------
age:張三
name:23

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章