Spring学习笔记(三)

 属性参考与自动绑定:
      <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
  "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="dateBean" class="java.util.Date"/> 
    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
        <property name="helloWord">
            <value>Hello!</value>
        </property>
        <property name="date">
            <ref bean="dateBean"/>
        </property>
    </bean>
</beans>
      在Spring的配置文件中,如果类中的属性是基本类型,那么在配置文件中就以<property name="helloWord"> <value>Hello!</value> </property> 这种方式定义,如果属性是某一个类就用<property name="date"> <ref bean="dateBean"/> </property> 这种方式定义。

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
  "http://www.springframework.org/dtd/spring-beans.dtd">

<beans> 
    <bean id="date" class="java.util.Date"/>
    <bean id="helloBean"
          class="onlyfun.caterpillar.HelloBean" 
         
autowite="byType".>
        <property name="helloWord">
            <value>Hello!</value>
        </property>
    </bean>
</beans>
autowite表示自动绑定,不用再定义档中声明,Spring会自动寻找xml与类中匹配的类型,还可以使用autowite="byName".autowire="constructor"表示在构造方法上实施绑定

集合物件注入:
      
      
對於像陣列、java.util.List、java.util.Set、java.util.Map等集合物件,在注入前必須填充入一些物件至集合中,然後再將集合物件注入至所需的Bean中,例如若有個Bean如下:

public class SomeBean {
    private String[] someStrArray;
    private SomeObj[] someObjArray;
    private List someList;
    private Map someMap;
}
對於這個需求,Spring也可以幫您維護,直接來看Bean定義檔如何設定:
<beans>
    <bean id="someBean" class="onlyfun.caterpillar.SomeBean">
        <property name="someArray">
            <list>
                <value>Hello!Justin!</value>
                <value>Hello!Momor!</value>
                <value>Hello!Bush!</value>
            </list>
        </property>
        <property name="someObjArray">
            <list>
                <ref bean="someObj1"/>
                <ref bean="someObj2"/>
            </list>
        </property>
        <property name="someList">
            <list>
                 <value>Hello!Justin!</value>
                 <ref bean="someObj1"/>
                 <ref bean="someObj2"/>
            </list>
        </property>
        <property name="someMap">
            <map>
                 <entry key="somekey1">
                     <ref bean="someObj1"/>
                 </entry>
                 <entry key="somekey2">
                     <value>Hello!Justin!</value>
                 </entry>
            </map>
        </property>
    </bean>
</beans>
      上面的Bean定義檔是個綜合示範,陣列與List物件都是用<list>標籤來設定,而Map物件使用<map>標籤設定,並需要一個key值設定
。 

      

你可能感兴趣的:(spring)