Spring bean map with dynamic keys and values
Right now I have application related data in spring bean and passed this map to other classes as a reference.
Map is defined 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 refers to other beans as
<bean id="config" class="com.example.Config" abstract="false">
<property name="sampleMap" ref="sampleMap"/>
.
.
</bean>
I just want to get the map values from a database table and want to insert them into other classes. How can I do this in spring. Basically, this table contains data related to the application. Map key and values will be int, Configuration.
What's the best place to load configuration data? can we do with the map the spring beans or is there any other good approach to load the configuration from the database and reference it elsewhere in the application like service, delegate and DAO?
Help would be appreciated
thank
source to share
You have to use spring 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>
source to share
FactoryBean's answer is correct, but it's the old way of doing things .
Use the class instead @Configuration
@Configuration
public class DBConfiguration{
@Autowired
private DataSource dataSource;
@Bean
public Map<Integer, Float> configMap(){
// use dataSource to get map values
}
}
One of the many advantages of this approach is that you can autwire DataSource
into a config class.
By the way, using the map as a bean doesn't seem right. I would create a wrapper object around the map and use it as a Spring Bean, but opinions differ on this.
source to share