spring心得4--setter注入集合(set、list、map、properties等多種集合,配有案例解析)@基本裝

y_keven發表於2013-04-25

1. 基本裝配

 

    在spring容器內拼湊bean叫做裝配。裝配bean的時候,需要告訴容器哪些bean以及容器如何使用依賴注入將它們配合在一起。

  使用XML裝配(xml是最常見的spring應用系統配置源。)

   幾種spring容器都支援使用xml裝配bean,包括:

   1).XmlBeanFactory:呼叫InputStream載入上下文定義檔案。

   2).ClassPathXmlApplicationContext:從類路徑載入上下文定義檔案。

   3).XmlWenApplicationContext:從web應用上下文中載入定義檔案。

   上下文定義檔案的根元素是<beans>.<beans>有多個<bean>子元素。每個<bean>元素定義了一個bean如何被裝配到spring容器中。對bean的最基本的配置包括bean的ID和他的全稱類名

基本裝配-scope

   scope屬性的值有以下五種:prototype、singleton、request session、global-session。

   spring中的bean預設情況下是單例模式始終返回一個例項。若想返回不同的例項的話需要定義成原型模式


 2.例項化與銷燬

    spring例項化bean或銷燬bean時,有時需要作一些處理工作,因此spring可以在建立和拆卸bean的時候呼叫bean的兩個生命週期方法(bean的宣告週期在上篇部落格有重墨講解)。

  <bean class="Foo" init-method destory-method>

  <bean class="...CommonAnnotationBeanPostProcessor">

   spring也提供了兩個介面來實現相同的功能:

  InitializingBean和DisposableBean.InitializingBean介面提供了一個afterPropertiesSet()方法。DisposableBean介面提供了destroy().不推薦使用該介面,它將你的bean和springAPI邦定在一起。

3.一些注意事項

    繼承配置(繼承在bean標籤加屬性parent屬性加以指明,該屬性值為繼承父類bean的id),覆蓋父 Bean配置。

   可以設定 <bean> 的abstract 屬性為 true, Spring 不會例項化該Bean有些屬性不會被繼承. 比如: autowire, abstract 等.子Bean 指定自己的class. 但此時 abstract 必須設為 true

   通過set方法依賴注入

   <bean>元素的< property >子元素指明瞭使用它們的set方法來注入。可以注入任何東西,從基本型別到集合類,甚至是應用系統的bean

   配置bean的簡單屬性,基本資料型別和string。

   在對應bean例項的property子標籤中設定一個bean型別的屬性;這種方式的缺點是你無法在其它地方重用這個bar例項,原因是它是專門為foo而用。

4.setter注入集合

  裝配List和陣列:

  <property name="barlist">

       <list>

           <value>bar1</value>

           <ref bean="bar2"/>

       </list>

  </property>

 裝配set

  <property name="barlist">

       <set>

           <value>bar1</value>

           <ref bean="bar2"/>

       </set>

  </property>

     set使用方法和list一樣,不同的是物件被裝配到set中,而list是裝配到List或陣列中裝配

 裝配map

  <property name="barlist">

       <map>

           <entry key="key1" value="bar1" />

           <entry key="key2 value-ref="xxx" />

      </map>

  </property>

   key值必須是string的,key-ref可以是其他bean。

 設定null

  <property name="barlist">

         <null/>

  </property>

  注入集合的案例分析

    以下類中的屬性命名方式和訪問許可權修飾符都是為了做測試,比如下面屬性都是public型別的。實際開發中都是private型別,通過get方法來訪問屬性,這裡只是為了簡單測試 。

 執行結果:


 集合bean CollectionBean類

package www.csdn.spring.collection.set;

 

import java.util.List;

import java.util.Map;

import java.util.Properties;

import java.util.Set;

 

publicclass CollectionBean {

   

   //set集合

   public  Set<String> sets;

 

   publicvoid setSets(Set<String> sets) {

      this.sets = sets;

   }

 

   public CollectionBean() {

      System.out.println("初始化。。。。。");

      

   }

   

   //list集合

   public List<User> users;

 

   publicvoid setUsers(List<User> users) {

      this.users = users;

   }

   

   //map集合

   public Map<Integer,User> map;  

 

   publicvoid setMap(Map<Integer, User> map) {

      this.map = map;

   }

   

   //properties集合

   public Properties props;

 

   publicvoid setProps(Properties props) {

      this.props = props;

   }

   

}

  輔助類 user

package www.csdn.spring.collection.set;

 

publicclass User {

 

   public String name;

   public Integer age;

   publicvoid setName(String name) {

      this.name = name;

   }

   publicvoid setAge(Integer age) {

      this.age = age;

   }

   

   

}

測試類 TestBean

package www.csdn.spring.collection.set;

 

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Properties;

import java.util.Set;

 

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

publicclass TestBean {

 

   @Test

   publicvoid test() {

      ApplicationContext context = new ClassPathXmlApplicationContext("spring-collection.xml");

      CollectionBean bean = context.getBean("collectionBean",CollectionBean.class);

      

      //set集合

      Set<String> sets = bean.sets;

       //得到迭代器

       Iterator<String> it = sets.iterator();

       while(it.hasNext()){

          System.out.println(it.next());

       }

       

       System.out.println("-------------------------list集合------------------------");

     

       //list集合

       List<User> users = bean.users;

       for(User user : users){

          System.out.println(user.name+"---"+user.age);

       }

       

       System.out.println("--------------------------map集合------------------------");

        

       //map集合

       //方法一:

       Map<Integer,User> map = bean.map;

       //得到map的key鍵的set集合

       Set<Integer> setKeys = map.keySet();

      //得到key鍵的迭代器

       Iterator<Integer> itKeys = setKeys.iterator();

      //迭代鍵值

       while(itKeys.hasNext()){

          //得到一個具體鍵值

          Integer key = itKeys.next();

          //通過get(key)方法獲取到key值對應的value

          User user = map.get(key);

          System.out.println(key+"--"+user.name+"="+user.age);

       }

       System.out.println("========================");

       //方法二:

       Set<Entry<Integer,User>> setEntry = map.entrySet();

       Iterator<Entry<Integer,User>> itEntry = setEntry.iterator();

       while(itEntry.hasNext()){

          Entry<Integer,User> entry = itEntry.next();

          User user = entry.getValue();

          System.out.println(entry.getKey()+"---"+user.name+"="+user.age);

       }

          

       System.out.println("-------------------------properties集合------------------------");

        

       //properties集合

       Properties props = bean.props;

       Set<String> setProps = props.stringPropertyNames();

       Iterator<String> keyStr = setProps.iterator();

       while(keyStr.hasNext()){

          String key = keyStr.next();

          //通過getProperty(key)方法來獲取key對應的value值

          System.out.println(key+"----"+props.getProperty(key));

       }

   } 

 

}

  spring配置檔案

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans.xsd">

 

   <bean id="collectionBean" class="www.csdn.spring.collection.set.CollectionBean">

      <!-- set集合 -->

      <property name="sets">

         <set>

            <value>陳紅軍</value>

            <value>楊凱</value>

            <value>李偉</value>

            <value>小胖</value>

            <value>瀟灑</value>

         </set>

      </property>

 

      <!-- list集合 -->

      <property name="users">

         <array>

            <ref bean="u1" />

            <ref bean="u2" />

            <ref bean="u3" />

         </array>

         <!-- <list> <ref bean="u1"/> <ref bean="u2"/> <ref bean="u3"/> </list> -->

      </property>

 

      <!-- map集合 -->

      <property name="map">

         <map>

            <entry key="1" value-ref="u1" />

            <entry key="2">

                <ref bean="u2" />

            </entry>

            <entry key="3" value-ref="u3" />

         </map>

      </property>

 

      <!--properties集合 -->

      <property name="props">

         <props>

            <prop key="1">jdbc:oracle</prop>

            <prop key="2">jdbc:mysql</prop>

            <prop key="3">jdbc:access</prop>

         </props>

      </property>

 

   </bean>

 

   <bean id="u1" class="www.csdn.spring.collection.set.User">

      <property name="name" value="楊凱" />

      <property name="age" value="22" />

   </bean>

   <bean id="u2" class="www.csdn.spring.collection.set.User">

      <property name="name" value="瀟灑" />

      <property name="age" value="22" />

   </bean>

   <bean id="u3" class="www.csdn.spring.collection.set.User">

      <property name="name" value="紅軍" />

      <property name="age" value="28" />

   </bean>

 

</beans>


 

 

相關文章