Announcement Announcement Module
No announcement yet.
Referring to same non-singleton bean twice Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Referring to same non-singleton bean twice

    Consider the following:

    <bean id="bean1" class="bean1class">
    <property name="prop1" ref="bean2"/>
    <property name="prop2" ref="bean2"/>

    <bean id="bean2" class="bean2class" singleton="false"/>

    Is there a mechanism in Spring to assign a same bean instance to both properties of bean1 (something like <property name="prop2" ref="this.bean1"/>)? The snippet above would produce two beans of class 'bean2class', while the desired result would be exactly one created bean. Bean2 needs to be non-singleton so that every bean1 gets their own copy of bean2.

    Thanks in advance!

  • #2
    Easy solution would be to use only one Spring property and set the other one in afterPropertiesSet.


    • #3
      Thanks for the reply. That was not the answer I was looking for though.
      The problem is, how will I be able to reference the same non-singleton bean instance in multiple places. I know the following is not a valid spring definition, but perhaps illustrates better what I'm trying to do:

      <bean id="allItems" class="Items">

      <alias id="key1" reference="defaultkey"/>

      <property name="items">

      <bean class="Location">
      <property name="x" value="10"/>
      <property name="y" value="20"/>
      <property name="item" alias="key1">

      <bean class="Location">
      <property name="x" value="20"/>
      <property name="y" value="25"/>
      <property name="item">
      <bean class="DefaultDoor">
      <property name="key" alias="key1"/>



      • #4
        I don't understand your example really. I mean I do, but I don't understand what should be singleton where and what not.

        Anyway - if at config-writing time you know you need N instances of something where N is a known, finite number you don't need to use singleton="false", just create N singletons under different names and assign them as needed.

        If you need to dynamically create unknown number of instances then you need singleton="false", but reusing the same instance several times needs to be done manually. (There is no concept of "local singleton", if there is such thing in theory at all )