Create HashMap Spring XML Example

Create HashMap Spring XML Example

While working with Spring framework where you define object model as bean in your Spring context file, you could also define HashMap as bean in your XML definition as below:

<bean id="accessHashMap" class="com.javahonk.AccessHashMap" />

<bean id= "ricMap" class="java.util.HashMap">
	<constructor-arg>
		<map key-type="java.lang.String" value-type="java.lang.String">
			<entry key="0LIBOR1M" value="USD1MFSR=" />
			<entry key="0LIBOR2M" value="USD2MFSR=" />            
			<entry key="0LIBOR3M" value="USD3MFSR=" />
			<entry key="0LIBOR6M" value="USD1YFSR=" />
			<entry key="FEDFUNDS" value="USONFFE=" />
		</map>
	</constructor-arg>
</bean>

To access above definition from java class please use below:

  • AccessHashMap.java:
package com.javahonk;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Qualifier;

public class AccessHashMap {
	
	@Resource
	@Qualifier("ricMap")
	private Map<String, String> ricMap;
	
	public void printHashMapData(){
		System.out.println(ricMap);
	}

}
  • Test class to load context file and print its value:
package com.javahonk;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Java Honk
 *
 */
public class TestApp {
	
	private static final Logger LOGGER = LogManager.getLogger(TestApp.class.getName());
	
	public static void main(String[] args) {
		
		LOGGER.info("Application starting...");	
		
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
		
		context.getBean(AccessHashMap.class).printHashMapData();
		
		
		((AbstractApplicationContext) context).close();
	}
	
}

Please note: You can not use @Autowired if try to access Map in place of HashMap. You will have to use @Resource instead as shown above.

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *