SSM搭建-Spring之IOC的XML注入(5)

         林炳文Evankaka原創作品。轉載請註明出處http://blog.csdn.net/evankaka

        在定義了 JavaBean 裝載信息之後需要對其賦值。一個 JavaBean 的賦值可以通過構造方法完成初始化,或者通過 set()方法初始化和改變屬性值。下面分別介紹如何在 XML 中配置 JavaBean 的屬性爲構造方法和 set()方法傳遞參數。

本文工程下載

一、構造注入

在類被實例化的時候,它的構造方法被調用並且只能調用一次。所以它被用於類的初始化操作。<constructor-arg>是<bean>標籤的子標籤。通過其<value>子標籤可以爲構造
方法傳遞參數。現在以一個簡單的輸出學生信息的實例演示如何爲構造方法傳遞參數。

實例程序創建過程如下。
(1)建立 Student 接口,它是對學生類的簡單抽象。程序代碼如下

[java] 
  1. package com.linbingwen;  
  2.   
  3. public interface Student {  
  4.  public void printInfo();  
  5. }  

package com.linbingwen;

public interface Student {
 public void printInfo();
}
(2)建立實現 Student 接口的 Stu1 類,定義姓名、年齡、性別 3 個屬性和包含這 3個參數的構造方法,在實現接口的 printInfo()方法中輸出所有屬性信息。程序代碼如下
  1. package com.linbingwen;  
  2.   
  3. public class Stu1 implements Student {  
  4.     private String name;  
  5.     private String sex;  
  6.     private int age;  
  7.   
  8.     public Stu1(String name, String sex, int age) {  
  9.         super();  
  10.         this.name = name;  
  11.         this.sex = sex;  
  12.         this.age = age;  
  13.     }  
  14.   
  15.     public void printInfo() {  
  16.         System.out.println("姓名:" + name);  
  17.         System.out.println("年齡:" + age);  
  18.         System.out.println("性別:" + sex);  
  19.     }  
  20. }  
package com.linbingwen;

public class Stu1 implements Student {
	private String name;
	private String sex;
	private int age;

	public Stu1(String name, String sex, int age) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
	}

	public void printInfo() {
		System.out.println("姓名:" + name);
		System.out.println("年齡:" + age);
		System.out.println("性別:" + sex);
	}
}
( 3 ) applicationContext.xml 是 裝 配 JavaBean 的 配 置 文 件 , 它 通 過 3 個<constructor-arg>標籤爲構造方法傳遞兩個 String 類型和一個 int 類型的參數。程序代碼如下。


  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">  
  6.     <bean id="stu1" class="com.linbingwen.Stu1">  
  7.         <constructor-arg>  
  8.             <value>飛龍</value>  
  9.         </constructor-arg>  
  10.         <constructor-arg>  
  11.             <value></value>  
  12.         </constructor-arg>  
  13.         <constructor-arg>  
  14.             <value>26</value>  
  15.         </constructor-arg>  
  16.     </bean>  
  17. </beans>  
<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
	<bean id="stu1" class="com.linbingwen.Stu1">
		<constructor-arg>
			<value>飛龍</value>
		</constructor-arg>
		<constructor-arg>
			<value>男</value>
		</constructor-arg>
		<constructor-arg>
			<value>26</value>
		</constructor-arg>
	</bean>
</beans>
注意:這裏要把applicationContext.xml放在src文件夾下。添加Spring和包不懂看這裏
(4)創建 Info 類。它是實例的主類,負責載入容器,從容器中獲得 Stu1 類的實例,並調用 Stu1 類的 pringInfo()方法打印學生信息。程序代碼如下
  1. package com.linbingwen;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6.   
  7.   
  8. public class Info {  
  9.   
  10.     public static void main(String[] args) {  
  11.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");  
  12.         Student student = (Student) applicationContext.getBean("stu1");  
  13.         student.printInfo();  
  14.     }  
  15.   
  16. }  
實例運行結果如圖 所示。

        通過這個實例,可以看到容器通過多個<constructor-arg>標籤完成了對構造方法的傳參,但是如果標籤的賦值順序與構造方法中參數的順序或參數類型不同,程序會產生異常。<constructor-arg>標籤可以使用“index”屬性和“type”屬性解決此類問題。下面分別介紹這兩個屬性的用法。
type 屬性:可以指定參數類型以確定要爲構造方法的哪個參數賦值。當需要賦值的屬性在構造方法中沒有相同的類型時,可以使用這個參數。因此實例中 stu1 的配置信息可以
這樣寫:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">  
  5.     <bean id="stu1" class="com.linbingwen.Stu1">  
  6.         <constructor-arg>  
  7.             <value>飛龍</value>  
  8.         </constructor-arg>  
  9.         <constructor-arg>  
  10.             <value></value>  
  11.         </constructor-arg>  
  12.         <constructor-arg type="int">  
  13.             <value>26</value>  
  14.         </constructor-arg>  
  15.     </bean>  
  16. </beans>  
<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
	<bean id="stu1" class="com.linbingwen.Stu1">
		<constructor-arg>
			<value>飛龍</value>
		</constructor-arg>
		<constructor-arg>
			<value>男</value>
		</constructor-arg>
		<constructor-arg type="int">
			<value>26</value>
		</constructor-arg>
	</bean>
</beans>
index 屬性:用於指定構造方法的參數索引,指定當前<constructor-arg>標籤爲構造方法的那個參數賦值。因爲程序中含有兩個 String 類型的參數,type 屬性無法做判斷,
導致 name 和 sex 參數無法判斷正確性。這時需要設置 index 屬性定義賦值索引來指定構造方法的參數位置。修改後的 applicationContext.xml 配置文件內容如下。

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">  
  5.     <bean id="stu1" class="com.linbingwen.Stu1">  
  6.         <constructor-arg index="0">  
  7.             <value>飛龍</value>  
  8.         </constructor-arg>  
  9.         <constructor-arg index="1">  
  10.             <value></value>  
  11.         </constructor-arg>  
  12.         <constructor-arg type="int">  
  13.             <value>26</value>  
  14.         </constructor-arg>  
  15.     </bean>  
  16. </beans>  
<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
	<bean id="stu1" class="com.linbingwen.Stu1">
		<constructor-arg index="0">
			<value>飛龍</value>
		</constructor-arg>
		<constructor-arg index="1">
			<value>男</value>
		</constructor-arg>
		<constructor-arg type="int">
			<value>26</value>
		</constructor-arg>
	</bean>
</beans>
在修改後的代碼中,兩個 String 類型的參數通過“index”屬性指定了在構造方法中的位置,確保了傳參的正確性,第 3 個<constructor-arg>標籤的 type 屬性可以改寫成
“index=2”。現在的 3 個<constructor-arg>標籤可以隨意調換順序而不會影響到構造方法的正確賦值。<constructor-arg>標籤還有“ref”和“value”兩個屬性,分別用於引用其他 JavaBean和定義新值。由於使用構造方法在配置文件中定義 JavaBean 使用得不多,所以這兩個屬性不再介紹。

二、設值注入

一個簡單的 JavaBean 最明顯的規則就是以一個私有屬性對應 set()和 get()方法,來實現對屬性的封裝。既然 JavaBean 有 set()方法來設置 Bean 的屬性,spring 就會有相應的支持。除了爲構造方法傳遞參數的<constructor-arg>標籤之外,<property>標籤可以爲JavaBean 的 set()方法傳遞參數,即通過 set()方法爲屬性賦值。在上面的實例中再添加一個 Moniter 類。

設置 Moniter 類屬性和 set()/get()方法。程序代碼如下。

  1. package com.linbingwen;  
  2.   
  3. public class Moniter implements Student {  
  4.     private String name;  
  5.     private String sex;  
  6.     private int age;  
  7.   
  8.     public void printInfo() {  
  9.         System.out.println("姓名:" + name);  
  10.         System.out.println("年齡:" + age);  
  11.         System.out.println("性別:" + sex);  
  12.     }  
  13.   
  14.     public int getAge() {  
  15.         return age;  
  16.     }  
  17.   
  18.     public void setAge(int age) {  
  19.         this.age = age;  
  20.     }  
  21.   
  22.     public String getName() {  
  23.         return name;  
  24.     }  
  25.   
  26.     public void setName(String name) {  
  27.         this.name = name;  
  28.     }  
  29.   
  30.     public String getSex() {  
  31.         return sex;  
  32.     }  
  33.   
  34.     public void setSex(String sex) {  
  35.         this.sex = sex;  
  36.     }  
  37. }  
package com.linbingwen;

public class Moniter implements Student {
	private String name;
	private String sex;
	private int age;

	public void printInfo() {
		System.out.println("姓名:" + name);
		System.out.println("年齡:" + age);
		System.out.println("性別:" + sex);
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}
}
修改 applicationContext.xml 配置文件。添加名稱爲 Moniter 的 Java Bean 的定義,用<property>標籤的“name”屬性指定要操作的 JavaBean 的屬性,然後通過<property>的子標籤<value>爲屬性賦值。修改後的代碼如下。
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">  
  5.     <bean id="stu1" class="com.linbingwen.Stu1">  
  6.         <constructor-arg index="0">  
  7.             <value>飛龍</value>  
  8.         </constructor-arg>  
  9.         <constructor-arg index="1">  
  10.             <value></value>  
  11.         </constructor-arg>  
  12.         <constructor-arg type="int">  
  13.             <value>26</value>  
  14.         </constructor-arg>  
  15.     </bean>  
  16.   
  17.     <bean id="moniter" class="com.linbingwen.Moniter">  
  18.         <property name="age">  
  19.             <value>26</value>  
  20.         </property>  
  21.         <property name="name">  
  22.             <value>欣欣</value>  
  23.         </property>  
  24.         <property name="sex">  
  25.             <value></value>  
  26.         </property>  
  27.     </bean>  
  28. </beans>  
<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
	<bean id="stu1" class="com.linbingwen.Stu1">
		<constructor-arg index="0">
			<value>飛龍</value>
		</constructor-arg>
		<constructor-arg index="1">
			<value>男</value>
		</constructor-arg>
		<constructor-arg type="int">
			<value>26</value>
		</constructor-arg>
	</bean>

	<bean id="moniter" class="com.linbingwen.Moniter">
		<property name="age">
			<value>26</value>
		</property>
		<property name="name">
			<value>欣欣</value>
		</property>
		<property name="sex">
			<value>女</value>
		</property>
	</bean>
</beans>
程序運行結果如圖  所示


三、接口注入(interface injection)

接口注入指的就是在接口中定義要注入的信息,並通過接口完成注入。

具體步驟如下
①.編寫一個接口IBuniness,各種數據庫的注入將通過這個接口進行。代碼如下

  1. package ch3;  
  2.   
  3. public interface IBusiness {  
  4.   
  5.  public void createDI(DataBase db);  
  6. }  
package ch3;

public interface IBusiness {

 public void createDI(DataBase db);
}
②.任何想要使用數據庫實例的類都必須實現這個接口,業務邏輯類Business實現這個接口IBusiness。代碼如下
  1. package ch3;  
  2.   
  3. public class Business implements IBusiness {  
  4.   
  5.  private DataBase db;  
  6.  @Override  
  7.  public void createDI(DataBase db) {//接口注入  
  8.   this.db = db;  
  9.  }  
  10. // 根據注入的數據庫,從XXX數據庫中取得數據。  
  11.  public void getData(){  
  12.   db.getData();  
  13.  }  
  14. }  
package ch3;

public class Business implements IBusiness {

 private DataBase db;
 @Override
 public void createDI(DataBase db) {//接口注入
  this.db = db;
 }
// 根據注入的數據庫,從XXX數據庫中取得數據。
 public void getData(){
  db.getData();
 }
}
3.編寫測試類TestBusiness。代碼如下

  1. package ch3;  
  2. public class TestBusiness {  
  3.  private Business business = new Business();  
  4. // 根據注入的數據庫類,從oracle中取得數據庫。  
  5.  public void getData() {  
  6.   business.createDI(new OracleDataBase()); // 注入實際的數據庫類型。如要變更式樣,只需改變此處即可,達到重用目的。  
  7.   business.getData();  
  8.  }  
  9. }  
如果要完成依賴關係注入的對象,必須實現IBusiness接口。

四、JavaBean 的賦值標籤

以上只介紹瞭如何用<value>標籤賦值,那麼複雜的屬性如何賦值呢?例如 Null、對象引用、集合類等。接下來將要介紹對 JavaBean 的複雜屬性賦值的標籤,它們可以應用到
任何如<constructor-arg>和<property>可以給 JavaBean 的屬性賦值的標籤中。
1.<value>標籤
這是一個普通的賦值標籤,可直接在成對的<value>標籤中放入數值或其他賦值標籤,Spring 會把這個標籤提供的屬性值注入到指定的 JavaBean 中。語法格式如下。

  1. <value>arg</value>  
<value>arg</value>
arg:傳遞給 JavaBean 的屬性值。
2.<ref>標籤
這個標籤可以引用其他 JavaBean 的實例對象,當傳遞的參數是其他 JavaBean 的實例對象時使用此標籤。語法格式如下。
  1. <ref bean="JavaBean"/>  
<ref bean="JavaBean"/>
bean:指定引用的 JavaBean。
3.<null>標籤
這是爲 JavaBean 賦 Null 空值的標籤。當 JavaBean 的某個屬性暫不使用,要將其設置爲 Null 值時使用此標籤。語法格式如下。
  1. <null/>  
<null/>

  1. <null></null>  
<null></null>
4.<list>標籤
這是爲 List 集合類或數組賦值的標籤。當 JavaBean 的某個屬性是 List 集合類型或數組時,需要使用此標籤爲 List 集合類型或數組的每一個元素賦值。語法格式如下。
  1. <list>  
  2.     <value>arg1</value>  
  3.     <value>arg2</value>  
  4. </list>  
<list>
    <value>arg1</value>
    <value>arg2</value>
</list>
<value>:賦值標籤,爲<list>標籤指定的屬性賦值。也可以使用其他賦值標籤作爲集合類賦值標籤的子標籤,例如<ref>或 3.2.7 節中介紹的使用<bean>標籤定義匿名內部
JavaBean 的方法。此標籤應用在<bean>標籤中定義 JavaBean 的完整代碼舉例如下。
  1. <bean id="school" class="School">  
  2.     <property name="studentList">  
  3.       <list>  
  4.         <ref bean=" student1"/>  
  5.         <value>student2</value>  
  6.       </list>  
  7.      </property>  
  8. </bean>  
<bean id="school" class="School">
    <property name="studentList">
      <list>
        <ref bean=" student1"/>
        <value>student2</value>
      </list>
     </property>
</bean>
5.<set>標籤
和<list>標籤類似,<set>標籤也是爲集合對象賦值,不過賦值的對象是 Set 類型的屬性。語法格式如下。

  1. <set>  
  2.     <ref bean="arg1"/>  
  3.     <value>arg2</value>  
  4. ……  
  5. </set>  
<set>
    <ref bean="arg1"/>
    <value>arg2</value>
……
</set>
此標籤應用在<bean>標籤中定義 JavaBean 的完整代碼舉例如下
  1. <bean id="school" class="School">  
  2.     <property name="student">  
  3.       <set>  
  4.         <ref bean=" student1"/>  
  5.         <value>name</value>  
  6.       </set>  
  7.     </property>  
  8. <bean>  
<bean id="school" class="School">
    <property name="student">
      <set>
        <ref bean=" student1"/>
        <value>name</value>
      </set>
    </property>
<bean>
6.<map>標籤
此標籤爲 Map 集合賦值。因爲 Map 以鍵值對(key/value)的方式存放數據,所以需要使用<entry>子標籤裝載 key 與 value 數據。Map 集合的 key 可以是任何類型的對象,而<entry>標籤的屬性 key 是以 String 類型表示的,所以限制了 Spring 中 Map 的 key 只能用 String 來表示。語法格式如下。
  1. <map>  
  2.     <entry key="key1">  
  3.     <ref bean="arg1" />  
  4.     </entry>  
  5. </map>  
<map>
    <entry key="key1">
    <ref bean="arg1" />
    </entry>
</map>
<entry>:<map>標籤的子標籤,其“key”屬性用於指定 Map 集合類的鍵值(key)。此標籤應用在<bean>標籤中定義 JavaBean 的完整代碼舉例如下。
  1. <bean id="school" class="School">  
  2.   <property name="student">  
  3.     <map>  
  4.       <entry key="key1">  
  5.       <ref bean=" student1" />  
  6.       </entry>  
  7.       <entry key="key2">  
  8.       <value> student2</value>  
  9.       </entry>  
  10.    </map>  
  11. </property>  
  12. </bean>  
<bean id="school" class="School">
  <property name="student">
    <map>
      <entry key="key1">
      <ref bean=" student1" />
      </entry>
      <entry key="key2">
      <value> student2</value>
      </entry>
   </map>
</property>
</bean>
7.<props>標籤
這是爲 java.util.Properties 類型屬性賦值的標籤,和<map>標籤類似,但是它的(key/value)鍵值全都是 String 類型的,無法賦予 Object 對象類型。語法格式如下。
  1. <props>  
  2. <prop key="key1">value</prop>  
  3. </props>  
<props>
<prop key="key1">value</prop>
</props>
<prop>:<props>的子標籤,其“key”屬性用於指定 Properties 類的鍵值(key)。此標籤應用在<bean>標籤中定義 JavaBean 的完整代碼舉例如下。
  1. <bean id="school" class="School">  
  2.     <property name="student">  
  3.         <props>  
  4.           <prop key="key1">student1</prop>  
  5.           <prop key="key2">student2</prop>  
  6.          </props>  
  7.      </property>  
  8. </bean>  
<bean id="school" class="School">
    <property name="student">
        <props>
          <prop key="key1">student1</prop>
          <prop key="key2">student2</prop>
         </props>
     </property>
</bean>
8 匿名內部 JavaBean 的創建
通過前面的介紹,讀者應該對如何使用 XML 裝配 JavaBean 有了一定的瞭解。但是編程中經常遇到匿名的內部類,在 Spring 中該如何利用 XML 裝配呢?其實非常簡單,在需要匿名內部類的地方直接用<bean>標籤定義一個內部類即可。如果要使這個內部類匿名,可以不指定<bean>標籤的 id 或 name 屬性。例如下面這段代碼:
  1. <bean id="school" class="School">  
  2.  <property name="student">  
  3.     <bean class="Student"/> <!--定義學生匿名內部類-->  
  4.  </property>  
  5. </bean>  
<bean id="school" class="School">
 <property name="student">
    <bean class="Student"/> <!--定義學生匿名內部類-->
 </property>
</bean>
代碼中定義了匿名的 Student 類,將這個匿名內部類賦給了 school 類的實例對象。

五、 list、set、map注入使用範例

還是接上面的工程,新建一個School.Java,代碼如下:

  1. package com.linbingwen;  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.Set;  
  7.   
  8. public class School {  
  9.     private List listStu;  
  10.     private Set setStu;  
  11.     private Map mapStu;  
  12.   
  13.     public List getListStu() {  
  14.         return listStu;  
  15.     }  
  16.     public void setListStu(List listStu) {  
  17.         this.listStu = listStu;  
  18.     }  
  19.     public Set getSetStu() {  
  20.         return setStu;  
  21.     }  
  22.     public void setSetStu(Set setStu) {  
  23.         this.setStu = setStu;  
  24.     }  
  25.   
  26.       
  27.     public Map getMapStu() {  
  28.         return mapStu;  
  29.     }  
  30.     public void setMapStu(Map mapStu) {  
  31.         this.mapStu = mapStu;  
  32.     }  
  33.       
  34.     public void printSchool(){  
  35.         System.out.println("--------list--------");    
  36.         for (int i = 0; i < listStu.size(); i++) {    
  37.             System.out.println(listStu.get(i));    
  38.         }      
  39.         System.out.println("--------set--------");    
  40.         for(Object s : setStu){    
  41.             System.out.println(s);    
  42.         }     
  43.         System.out.println("--------map--------");    
  44.         Iterator it=mapStu.entrySet().iterator();            
  45.         System.out.println(mapStu.entrySet().size());      
  46.         String key;            
  47.         String value;     
  48.         while(it.hasNext()){     
  49.                 Map.Entry entry = (Map.Entry)it.next();            
  50.                 key=entry.getKey().toString();            
  51.                 value=entry.getValue().toString();            
  52.                 System.out.println(key+"===="+value);                      
  53.         }     
  54.     }  
  55. }  
package com.linbingwen;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class School {
	private List listStu;
	private Set setStu;
	private Map mapStu;

	public List getListStu() {
		return listStu;
	}
	public void setListStu(List listStu) {
		this.listStu = listStu;
	}
	public Set getSetStu() {
		return setStu;
	}
	public void setSetStu(Set setStu) {
		this.setStu = setStu;
	}

	
	public Map getMapStu() {
		return mapStu;
	}
	public void setMapStu(Map mapStu) {
		this.mapStu = mapStu;
	}
	
	public void printSchool(){
        System.out.println("--------list--------");  
        for (int i = 0; i < listStu.size(); i++) {  
            System.out.println(listStu.get(i));  
        }    
        System.out.println("--------set--------");  
        for(Object s : setStu){  
            System.out.println(s);  
        }   
        System.out.println("--------map--------");  
        Iterator it=mapStu.entrySet().iterator();          
        System.out.println(mapStu.entrySet().size());    
        String key;          
        String value;   
        while(it.hasNext()){   
                Map.Entry entry = (Map.Entry)it.next();          
                key=entry.getKey().toString();          
                value=entry.getValue().toString();          
                System.out.println(key+"===="+value);                    
        }   
	}
}
applicationContext.xml如下:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">  
  5.   
  6.     <bean id="stu1" name="student1" class="com.linbingwen.Stu1">  
  7.         <constructor-arg index="0">  
  8.             <value>飛龍</value>  
  9.         </constructor-arg>  
  10.         <constructor-arg index="1">  
  11.             <value>男</value>  
  12.         </constructor-arg>  
  13.         <constructor-arg type="int">  
  14.             <value>26</value>  
  15.         </constructor-arg>  
  16.     </bean>  
  17.   
  18.     <bean id="moniter" name="student2" class="com.linbingwen.Moniter">  
  19.         <property name="age">  
  20.             <value>26</value>  
  21.         </property>  
  22.         <property name="name">  
  23.             <value>欣欣</value>  
  24.         </property>  
  25.         <property name="sex">  
  26.             <value>女</value>  
  27.         </property>  
  28.     </bean>  
  29.   
  30.   
  31.     <bean id="school" class="com.linbingwen.School">  
  32.         <!--List 注入例子 -->  
  33.         <property name="listStu">  
  34.             <list>  
  35.                 <ref bean="moniter" />  <!--使用上面已定義好的bean -->  
  36.                 <ref bean="moniter" />  <!--使用上面已定義好的bean -->  
  37.                 <ref bean="stu1" />     <!--使用上面已定義好的bean -->  
  38.                 <bean class="com.linbingwen.Moniter"> <!--定義學生匿名內部類,用setter方法注入 -->  
  39.                     <property name="age" value="20" />  
  40.                     <property name="name" value="阿屁" />  
  41.                     <property name="sex" value="男" />  
  42.                 </bean>  
  43.                 <value>1</value>  
  44.                 <value>hello</value>  
  45.             </list>  
  46.         </property>  
  47.   
  48.         <!--set 注入例子 -->  
  49.         <property name="setStu">  
  50.             <set>  
  51.                 <ref bean="moniter" />  <!--使用上面已定義好的bean -->  
  52.                 <ref bean="stu1" />     <!--使用上面已定義好的bean -->  
  53.                 <ref bean="stu1" />     <!--使用上面已定義好的bean -->  
  54.                 <bean class="com.linbingwen.Stu1"> <!--定義學生匿名內部類,用constructor方法注入 -->  
  55.                     <constructor-arg value="大平" index="0"></constructor-arg>  
  56.                     <constructor-arg value="男" index="1"></constructor-arg>  
  57.                     <constructor-arg value="10" index="2"></constructor-arg>  
  58.                 </bean>  
  59.                 <value>333333</value>  
  60.                 <value>Evankaka</value>  
  61.             </set>  
  62.         </property>  
  63.   
  64.         <!--map 注入例子 -->  
  65.         <property name="mapStu">  
  66.             <map>  
  67.                 <entry key="key1">  
  68.                     <ref bean="moniter" />  <!--使用上面已定義好的bean -->  
  69.                 </entry>  
  70.                 <entry key="key2">  
  71.                    <bean class="com.linbingwen.Moniter"> <!--定義學生匿名內部類,用setter方法注入 -->  
  72.                     <property name="age" value="80" />  
  73.                     <property name="name" value="小王" />  
  74.                     <property name="sex" value="男" />  
  75.                 </bean>  
  76.                 </entry>  
  77.                 <entry key="key3">  
  78.                     <value>student2</value>  
  79.                 </entry>  
  80.                 <entry key="key4">  
  81.                     <value>56</value>  
  82.                 </entry>  
  83.             </map>  
  84.         </property>  
  85.   
  86.     </bean>  
  87. </beans>  
<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

	<bean id="stu1" name="student1" class="com.linbingwen.Stu1">
		<constructor-arg index="0">
			<value>飛龍</value>
		</constructor-arg>
		<constructor-arg index="1">
			<value>男</value>
		</constructor-arg>
		<constructor-arg type="int">
			<value>26</value>
		</constructor-arg>
	</bean>

	<bean id="moniter" name="student2" class="com.linbingwen.Moniter">
		<property name="age">
			<value>26</value>
		</property>
		<property name="name">
			<value>欣欣</value>
		</property>
		<property name="sex">
			<value>女</value>
		</property>
	</bean>


	<bean id="school" class="com.linbingwen.School">
		<!--List 注入例子 -->
		<property name="listStu">
			<list>
				<ref bean="moniter" />  <!--使用上面已定義好的bean -->
				<ref bean="moniter" />  <!--使用上面已定義好的bean -->
				<ref bean="stu1" />     <!--使用上面已定義好的bean -->
				<bean class="com.linbingwen.Moniter"> <!--定義學生匿名內部類,用setter方法注入 -->
					<property name="age" value="20" />
					<property name="name" value="阿屁" />
					<property name="sex" value="男" />
				</bean>
				<value>1</value>
				<value>hello</value>
			</list>
		</property>

		<!--set 注入例子 -->
		<property name="setStu">
			<set>
				<ref bean="moniter" />  <!--使用上面已定義好的bean -->
				<ref bean="stu1" />     <!--使用上面已定義好的bean -->
				<ref bean="stu1" />     <!--使用上面已定義好的bean -->
				<bean class="com.linbingwen.Stu1"> <!--定義學生匿名內部類,用constructor方法注入 -->
					<constructor-arg value="大平" index="0"></constructor-arg>
					<constructor-arg value="男" index="1"></constructor-arg>
					<constructor-arg value="10" index="2"></constructor-arg>
				</bean>
				<value>333333</value>
				<value>Evankaka</value>
			</set>
		</property>

		<!--map 注入例子 -->
		<property name="mapStu">
			<map>
				<entry key="key1">
					<ref bean="moniter" />  <!--使用上面已定義好的bean -->
				</entry>
				<entry key="key2">
                   <bean class="com.linbingwen.Moniter"> <!--定義學生匿名內部類,用setter方法注入 -->
                    <property name="age" value="80" />
                    <property name="name" value="小王" />
                    <property name="sex" value="男" />
                </bean>
                </entry>
				<entry key="key3">
					<value>student2</value>
				</entry>
				<entry key="key4">
                    <value>56</value>
                </entry>
			</map>
		</property>

	</bean>
</beans>
如下:

[java] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. package com.linbingwen;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. public class Info {  
  7.   
  8.     public static void main(String[] args) {  
  9.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");  
  10.         Student student = (Student) applicationContext.getBean("stu1");  
  11.         student.printInfo();  
  12.         Student moniter = (Student) applicationContext.getBean("moniter");  
  13.         moniter.printInfo();  
  14.         School school=(School) applicationContext.getBean("school");  
  15.         school.printSchool();  
  16.     }  
  17.   
  18. }  
package com.linbingwen;

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

public class Info {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		Student student = (Student) applicationContext.getBean("stu1");
		student.printInfo();
		Student moniter = (Student) applicationContext.getBean("moniter");
		moniter.printInfo();
		School school=(School) applicationContext.getBean("school");
		school.printSchool();
	}

}
輸出結果:

四月 02, 2015 5:36:38 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@addb54: startup date [Thu Apr 02 17:36:38 CST 2015]; root of context hierarchy
四月 02, 2015 5:36:38 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
四月 02, 2015 5:36:38 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ebcd03: defining beans [stu1,moniter,school]; root of factory hierarchy
姓名:飛龍
年齡:26
性別:男
姓名:欣欣
年齡:26
性別:女
--------list--------
姓名:欣欣;年齡:26;性別:女
姓名:欣欣;年齡:26;性別:女
姓名:飛龍;年齡:26;性別:男
姓名:阿屁;年齡:20;性別:男
1
hello
--------set--------
姓名:欣欣;年齡:26;性別:女
姓名:飛龍;年齡:26;性別:男
姓名:大平;年齡:10;性別:男
333333
Evankaka
--------map--------
4
key1====姓名:欣欣;年齡:26;性別:女
key2====姓名:小王;年齡:80;性別:男
key3====student2
key4====56


六、 總結


 設值注入和構造注入的比較

 1、設值注入的優點

(1)與傳統的JavaBean的寫法更相似,更容易讓人理解,依賴關係顯得更加直觀、自然。

(2)對於複雜的依賴關係,如果採用構造注入會導致構造器過於臃腫,難以閱讀。因爲Spring在創建Bean實例時,需要同時實例化其依賴的全部實例,因而導致Struts+Spring+hibernate整合開發性能下降。設值注入可以避免這些問題。

(3)在某些屬性可選的情況下,多參數的構造器更加笨重。

 2、構造注入的優點

(1) 可以在構造器中決定依賴關係的注入順序。例如,組件中其他依賴關係的注入,常常需要依賴於Datasource的注入。採用構造注入時,可以在代碼中清晰地決定注入順序,優先依賴先注入。

(2)對於依賴關係無須變化的bean,構造注入更有用處。因爲沒有setter,所有的關係都在構造器中設定,因此無需擔心後續代碼對依賴關係產生破壞。

(3) 依賴關係只能在構造器中設定,因爲只有組件的創建者才能改變組件的依賴關係。對於組件的調用者而言,組件內部的依賴關係完全透明,更符合高內聚的原則。

建議採用設值注入爲主,構造注入爲輔的注入策略。

Spring Bean的其他說明

1、 Bean的標識(id,name,class)

id:bean的唯一標識。

2、name:bean的別名,可以有多個。

class:bean的具體實現類

3、 Bean的作用域

(1) singleton:單例,在IOC容器裏只有一個實例

  1. <!-- 默認 -->  
  2. <beanidbeanid="loginAction"class="net.vzhang.spring3.action.LoginAction" scope="singleton"/>  

(2) prototype:

  1. <beanidbeanid="loginAction2"class="net.vzhang.spring3.action.LoginAction2" scope="prototype"/>  
<beanid="loginAction2"class="net.vzhang.spring3.action.LoginAction2" scope="prototype"/>
request:針對Web應用的每次請求都生成一個新的實例

每次對bean請求時,都會創建一個新的實例。

對bean的請求:將其注入到另外一個bean中,或者調用BeanFactory的getBean方法。

 session:HttpSessio

 

本文工程下載

  林炳文Evankaka原創作品。轉載請註明出處http://blog.csdn.net/evankaka

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