使用 spring bean xml 初始化自定义内部对象

Init Custom inner object using spring bean xml

我有这种class:

Class Food
  int type
  String name

Class Dog
   String dogName
   Food food

我想使用 Spring 属性初始化 Dog class,我可以通过以下方式初始化 dogName 值:

<bean id="dog" class="....Dog"> 

 <property name="dogName" value="dog"/> 

...

</bean>

如何为 Food 对象设置值?

使用<property>中的ref来引用食物的bean id。

<bean id="food" class="....Food"> 

</bean>

<bean id="dog" class="....Dog"> 
    <property name="dogName" value="dog"/> 
    <property name="food" ref="food"/> 
</bean>
<property name="food">
    <bean class="...Food">
      <property name="type" value="1"/>
      <property name="name" value="Apple"/>          
    </bean>
  </property>

参见Spring 3.3.2.3. Inner beans:

A element inside the or elements is used to define a so-called inner bean. An inner bean definition does not need to have any id or name defined, and it is best not to even specify any id or name value because the id or name value simply will be ignored by the container.

<bean id="outer" class="...">
  <!-- instead of using a reference to a target bean, simply define the target bean inline -->
  <property name="target">
    <bean class="com.example.Person"> <!-- this is the inner bean -->
      <property name="name" value="Fiona Apple"/>
      <property name="age" value="25"/>
    </bean>
  </property>
</bean>

使用ref in 来引用食物的bean id。

    <bean id="food" class="....Food"></bean>

    <bean id="dog" class="....Dog"> 
        <property name="dogName" value="dog"/> 
        <property name="food" ref="food"/> 
    </bean>

     <bean id="dog" class="c...dog">
        <property name="dogName" value="dog"/> 
        <property name="food" >
            <bean  class="...food">
               <property name="type" value="1"/> 
               <property name="name" value="chicken"/> 
            </bean>
        </property>
     </bean>

在 inner 的情况下,你不能在父 bean 标签之外使用它

 <bean id="dog" class="c...dog">
    <property name="dogName" value="dog"/> 
    <property name="food" >
        <bean  class="...food">
           <property name="type" value="1"/> 
           <property name="name" value="chicken"/> 
      </bean>
    </property>
</bean>