Spring bean map with dynamic keys and values

Javee picture Javee · Feb 4, 2013 · Viewed 14.4k times · Source

Right now i've application related data in spring bean map and passed this map to other classes as ref.

Map is defined as below

<bean id="sampleMap" class="java.util.HashMap">
    <constructor-arg index="0" type="java.util.Map">
        <map key-type="java.lang.Integer" value-type="java.lang.Float">
            <entry key="1" value="5"/>
            <entry key="2" value="10"/>
            <entry key="3" value="15"/>             
        </map>
    </constructor-arg>
</bean>

This map is referred in other beans as

<bean id="config" class="com.example.Config" abstract="false">      
    <property name="sampleMap" ref="sampleMap"/>
    .
    .
</bean>

I just want to retrieve the map values from database table and want to inject that to other classes. How can i do that in spring. Basically that table contains application related data.The key and values of map will be int,Configuration.

What is the best place to load the configuration data? can we do with spring beans map or is there any other good approach to load configuration from database and refer that in other places of application like service,delegate and DAO?

Help will be appreciated

Thanks

Answer

kan picture kan · Feb 4, 2013

You should use spring's FactoryBean.

public class MyHashMapFactoryBean implements FactoryBean<Map<Integer, Float>>{

  @Autowired
  private Datasource datasource; 

  public Map<Integer, Float> getObject(){
    return <load from database>;
  }

  public Class<Map> getObjectType() { return Map.class ; }

  public boolean isSingleton() { return true; }
}

<bean id="sampleMap" class="my.package.MyHashMapFactoryBean">
  <here you could pass some properties e.g. jdbc datasource>
</bean>