spring配置中property作為bean的屬性。也就是指一個類中的成員。同時這個成員必須有get和set方法。
property的一般用法:
<bean id="playerDataManager" class="com.cp.game.PlayerDataManager" init-method="init" scope="singleton">
<property name="sleepTime" value="${app.dispatcher.sleepTime}" /> //從外部的property文件中用el表達式獲取值
<property name="sleepTime" value="333" /> //直接在賦值
<property name="playerDao" ref="playerDao" /> 引用其他bean對象。 ref的值是其他bean的id名
//內部嵌套bean的用法
<property name="messageExecutor"> <bean class="com.cp.netty.domain.FiexThreadPoolExecutor" destroy-method="shutdown"> <constructor-arg value="${app.dispatcher.pool.corePoolSize}" /> <constructor-arg value="${app.dispatcher.pool.maximumPoolSize}" /> <constructor-arg value="${app.dispatcher.pool.keepAliveSecond}" /> </bean> </property>
有多個值的property配置(相當於集合)
<property name="locations"> <list> <value>config/settings.properties</value> <value>classpath:c3p0.properties</value> <value>classpath:mchange-log.properties</value> <value>classpath:mchange-commons.properties</value> </list> </property>
注入集合屬性,使用list,map,set和props標簽,分別對應List,Map,Set和Properties: <bean id="injectCollection" class="com.apress.prospring.ch4.CollectionInjection"> <property name="map"> <map> <entry key="someValue"> <value>Hello World!</value> </entry> <entry key="someBean"> <ref local="oracle"/> </entry> </map> </property> <property name="props"> <props> <prop key="firstName"> Rob </prop> <prop key="secondName"> Harrop </prop> </props> </property> <property name="set"> <set> <value>Hello World!</value> <ref local="oracle"/> </set> </property> <property name="list"> <list> <value>Hello World!</value> <ref local="oracle"/> //表示在本配置文件中查找bean。后面有詳細講解 </list> </property> </bean>
</bean>
進階問題:
<property name="a" ref="b" />和<property name="a" > <ref bean="b" /> </property>這兩種方式有啥不一樣的?
spring的配置文件可能會有多個
<property name="a" ref="b" />就是找當前配置文件里的bean 也就是b
<ref bean ="b"/> 是尋找全局中的 bean;就是說<ref 可以查找別的XML配置文件中的bean。這樣是可以找到其他配置文件定義id為b的bean的
也可以想到 在工作中一個項目spring的配置文件 肯定有好幾個用<ref bean="b" /> 來關聯指定在其他xml文件中的bean很方便而且不容易出錯
其實<ref標簽里 有3種屬性 <ref bean=""/>,<ref local=""/>,<ref parent=""/>
而第一種不用說了
第二種就是關聯當前xml的bean 也就等同於<property name="a" ref="b" />這種寫法
而第三種就是 用於指定其依賴的父 JavaBean 定義。