Enjoying this Java & Spring tutorial?
Subscribe to Ram N Java on YouTubeIntroduction
In Spring applications, you often need to pass key-value collections to configure components. Spring's IoC container provides built-in support for mapping key-value pairs directly into a java.util.Map using constructor dependency injection.
In this tutorial, you will learn how to configure and inject a basic Map with String keys and values into a Java class via its constructor.
1. Create the Java Bean Class
Create a model or service class (such as FruitShop) that accepts a Map<String, String> inside its constructor:
import java.util.Map;
public class FruitShop {
private String shopName;
private Map<String, String> fruitsMap;
public FruitShop(String shopName, Map<String, String> fruitsMap) {
this.shopName = shopName;
this.fruitsMap = fruitsMap;
}
public void displayFruitShopInfo() {
System.out.println("Shop Name: " + shopName);
System.out.println("Fruits Inventory:");
for (Map.Entry<String, String> entry : fruitsMap.entrySet()) {
System.out.println("Code: " + entry.getKey() + " -> Name: " + entry.getValue());
}
}
}
2. Configure Spring XML with <map> and <entry>
In your applicationContext.xml, configure the bean using the <constructor-arg> element along with the <map> and <entry> sub-elements:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="fruitShop" class="FruitShop">
<constructor-arg value="City Fresh Supermarket" />
<constructor-arg>
<map>
<entry key="F101" value="Apple" />
<entry key="F102" value="Orange" />
<entry key="F103" value="Banana" />
</map>
</constructor-arg>
</bean>
</beans>
3. Load Context and Run the Application
Use ClassPathXmlApplicationContext to bootstrap the Spring IoC container, retrieve the configured bean, and execute the display method:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
FruitShop shop = (FruitShop) context.getBean("fruitShop");
shop.displayFruitShopInfo();
}
}
Watch More Spring Tutorials
Click here to watch on Youtube:
https://www.youtube.com/watch?v=s6ilFjOYfMk&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge:
| How to Inject Map using Spring dependency injection by constructor? | Spring Tutorial |
| How to Inject Map using Spring dependency injection by constructor? | Spring Tutorial |
| How to Inject Map using Spring dependency injection by constructor? | Spring Tutorial |
| How to Inject Map using Spring dependency injection by constructor? | Spring Tutorial |
No comments:
Post a Comment