Spring依賴注入 — util命名空間配置

要使用<util>標籤,必須在XML中加入util名稱空間(namespace):html

xmlns:util="http://http://www.springframework.org/schema/util"

xsi:schemaLocation="http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-2.0.xsd"

 

分別使用<util:list>、<util:map>、<util:set>、<util:properties>等標籤。java

用它來取代ListFactoryBean、MapFactoryBean、SetFactoryBean、PropertiesFactoryBean。spring

其中的<util:properties>標籤能夠經過location屬性指定其properties屬性文件的位置。spa

 

除了以上使用的標籤外,還有<util:constant>可用來設置靜態數據成員(staticfield),而免於設置org.springframework.beans.factory.config.FieldRetrievingFactoryBean,例如:code

<bean id="circle" class="cn.itcast.spring._other.Circle">

<property name="pi">

<util:constant static-field="java.lang.Math.PI"/>

</property>

</bean>

  

 

 

還可使用<util:property-path>標籤爲某個Bean的屬性成員設置id屬性,使之在容器管理中,免於設置org.springframework.beans.factory.config.PropertyPathFactoryBean,例如:xml

<!-- id值爲PI的Bean,其值將會是circle.pi -->

<util:property-path  id="PI" path="circle.pi"/>

 

修改集合對象中示例的Bean定義文件htm

<bean id="some1" class="cn.itcast.spring._util.Some">

  <property name="val" value="some instance1" />

</bean>

<bean id="some2" class="cn.itcast.spring._util.Some">

  <property name="val" value="some instance2" />

</bean>

<bean id="some3" class="cn.itcast.spring._util.Some">

  <property name="val" value="some instance3" />

</bean>

<util:list id="strArray">

  <value>Hello</value>

  <value>Welcome</value>

</util:list>

<util:list id="objArray">

  <ref bean="some1" />

  <ref bean="some2" />

  <ref bean="some3" />

</util:list>

<util:list id="list" list-class="java.util.ArrayList">

  <ref bean="some1"/>

  <ref bean="some2" />

  <ref bean="some3" />

</util:list>

<util:map id="map" map-class="java.util.HashMap" >

  <entry key="key1" value-ref="some1"/>

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

  <entry key="key3" value-ref="some3"/>

</util:map>

 寫完util配置文件後,如何給某個類賦值呢?也能夠直接用配置的方式:對象

<bean id="someBean" class="cn.itcast.spring._util.SomeBean">

  <property name="someStrArray" ref="strArray"/>

  <property name="someObjArray" ref="objArray"/>

  <property name="someList" ref="list"/>

  <property name="someMap" ref="map"/>

</bean>

或者在類中使用@Value註解blog

@Value("#{strArray}")
private List<String> somoeStrArray;
@Value("#{objArray}")
private List<Some> somoeObjArray;
@Value("#{list}")
private List<Some> somoeList;
@Value("#{map}")
private Map<String,Some> someMap;
相關文章
相關標籤/搜索