spring中property 设值注入

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 定义。
 
原文地址:https://www.cnblogs.com/sanhuan/p/4788993.html