Search code examples
javaxmlhashmaposgiblueprint-osgi

Defining a hashmap as a bean


I am trying to define a HashMap as a bean on blueprint xml. The original problem is that I have

<bean id="class1" class="com.acme.Class1">
  <property name="acmeMap">
    <map>
      <entry-key="coyotte" value="Poor Fellow"/>
      <entry-key="roadRunner" value="Sadistic Bird"/>
    </map>
  </property>
</bean>

and it works well. Problem is when I have also another class which extends Class1, for example Class1a, on the same blueprint xml file.

<bean id="class1a" class="com.acme.Class1a">
  <property name="acmeMap">
    <map>
      <entry-key="coyotte" value="Poor Fellow"/>
      <entry-key="roadRunner" value="Sadistic Bird"/>
    </map>
  </property>
</bean>

This means defining the map twice and having to maintain it on the blueprint xml. Is there no way to instantiate, for example, something like

 <bean id="acmeMap" class="java.util.HashMap"/> 

and initialize it with the values I need and then import the reference on the other beans? That would mean acmeMap is only created once. I did search for examples of initializing blueprint bean maps on the internet and can't find one. Or maybe the solution is something else?


Solution

  • You can make use of the parent tag to specify the inheritance and get a control over the properties defined in the class. Either you can reuse the same or define the new one.You can refer the below example.

    <bean id="bean1" class="MyBean">
        <property name="attrib1" value="val1" />
        <property name="attrib2" value="val2" />
    </bean>
    <bean id="bean2" parent="bean1">
        <property name="attrib3" value="val3" />
        <property name="attrib4" value="val4" />
    </bean>