Store class HashMap Spring Example

Store class HashMap Spring Example

Spring provide many functionality which can be configured and access at run time through beans. Here I will show you how to store classes in HashMap and access it at runtime.

We will use below two classes which will implement same interface:

  • TestInterface.java:
package com.javahonk;

public interface TestInterface {

	void printSomeValue();
}
  • TestInterfaceImpl.java:
package com.javahonk;

public class TestInterfaceImpl implements TestInterface{

	public void printSomeValue() {
		System.out.println("Java Honk TestInterfaceImpl class");
		
	}

}
  • TestInterfaceImpl2.java:
package com.javahonk;

public class TestInterfaceImpl2 implements TestInterface{

	public void printSomeValue() {
		System.out.println("Java Honk TestInterfaceImpl2 class");
		
	}

}
  • Now define bean for it and store in HashMap as below:
<bean id="accessClassesHashMap" class="com.javahonk.AccessClassesHashMap" />
<bean id="testInterfaceImpl" class="com.javahonk.TestInterfaceImpl" />
<bean id="testInterfaceImpl2" class="com.javahonk.TestInterfaceImpl2" />

<bean id= "classStoredMap" class="java.util.HashMap">
	<constructor-arg>
	<map key-type="java.lang.String" value-type="com.javahonk.TestInterface">
		<entry key="TEST_INTERFACE_IMPL" value-ref="testInterfaceImpl" />
		<entry key="TEST_INTERFACE_IMPL2" value-ref="testInterfaceImpl2" />
	</map>
	</constructor-arg>
</bean>

You could access HashMap and its classes as below:

  • AccessClassesHashMap.java:
package com.javahonk;

import java.util.Map;

import javax.annotation.Resource;

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

public class AccessClassesHashMap {
	
	@Resource
	@Qualifier("classStoredMap")
	private Map<String, TestInterface> classStoredMap;
	
	public void printHashMapData(){
		
		TestInterface testInterface = classStoredMap.get("TEST_INTERFACE_IMPL");
		testInterface.printSomeValue();
		
		testInterface = classStoredMap.get("TEST_INTERFACE_IMPL2");
		testInterface.printSomeValue();
		
		System.out.println("Values in hashmap: "+classStoredMap);
	}

}

Reference:

Leave a Reply

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