Working with Collection Element Type Map in Spring Application

With this example I will show you how to inject Collection Type Map in Spring Bean. I am going to show you in Spring Boot framework how to read map based key/value pair. I will also show you how to read the map based values from traditional XML config file.

In order to show how Collections can be injected in a Spring Bean I will create a simple Spring Bean with a property Map. For example, the map of elements are changeable over time or your application needs to update these configurable properties frequently without restarting your server.

Prerequisites

Java at least 8, Spring Boot 2.4.1, Maven 3.6.3, Gradle 6.7.1

Project Setup

You can create a gradle or maven based project in your favorite IDE or tool.

For gradle based project you can use the following build.gradle script:

buildscript {
	ext {
		springBootVersion = '2.4.1'
	}
	
    repositories {
    	maven {
    		url 'https://plugins.gradle.org/m2/'
    	}
    }
    
    dependencies {
    	classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

plugins {
    id 'java-library'
    id 'org.springframework.boot' version "${springBootVersion}"
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
	implementation("org.springframework.boot:spring-boot-starter:${springBootVersion}")
}

For maven based project you can use the following pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>spring-collection-map</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>12</maven.compiler.source>
		<maven.compiler.target>12</maven.compiler.target>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.1</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

Application Properties

Create src/main/resources folder if it does not exist already. Under this folder you need to create an application.properties file for map configuration.

Injecting Collection – Map

You generally configure key/value pairs in the properties file at each line and you inject these key/value pairs with the @ConfigurableProperties annotation or using Environment interface or using the @Value annotation but these are not formed as elements of map data structure.

Here I am going to show you how you can configure as map elements in the application.properties file.

map.elements={site:'https://roytuts.com',author:'Soumitra',about:'https://roytuts.com/about',facebook:'https://www.facebook.com/roytuts2014',twitter:'https://twitter.com/roytuts',youtube:'https://www.youtube.com/channel/UCMysotNzptWegWBSY9lox_g',ello:'https://ello.co/soumitrajuster',linkedin:'https://www.linkedin.com/in/soumitra-sarkar-80ba0328/'}

In Java configuration you need to pick these values in the following way:

@Value("#{${map.elements}}")
private Map<String, String> map;

The whole source code can be downloaded from the Source Code section later in this tutorial.

Another way is to use the traditional way of using the XML config to define a map with key/value elements and read this map in the class.

<?xml version="1.0" encoding="UTF-8"?>
<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="springCollectionMap"
		class="com.roytuts.spring.collection.map.RoytutsInfoMap">
		<property name="map">
			<map>
				<entry key="site" value="https://roytuts.com" />
				<entry key="author" value="Soumitra" />
				<entry key="about" value="https://roytuts.com/about" />
				<entry key="facebook"
					value="https://www.facebook.com/roytuts2014" />
				<entry key="twitter" value="https://twitter.com/roytuts" />
				<entry key="youtube"
					value="https://www.youtube.com/channel/UCMysotNzptWegWBSY9lox_g" />
				<entry key="ello" value="https://ello.co/soumitrajuster" />
				<entry key="linkedin"
					value="https://www.linkedin.com/in/soumitra-sarkar-80ba0328/" />
			</map>
		</property>
	</bean>
</beans>

The corresponding Java class for the above bean is given below:

package com.roytuts.spring.collection.map;

import java.util.Map;

public class RoytutsInfoMap {

	private Map<String, String> map;

	public Map<String, String> getMap() {
		return map;
	}

	public void setMap(Map<String, String> map) {
		this.map = map;
	}

}

Finally you can use the below configuration to load the XML based bean configuration in Spring Boot application:

@Configuration
@ImportResource("classpath:map.xml")
public class Config {

}

Main Class

A class with main method and @SpringBootApplication annotation is used to start the Spring Boot application. I am using CLI version for starting the app.

package com.roytuts.spring.collection.map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringCollectionMapApp implements CommandLineRunner {

	@Autowired
	private SpringCollectionMap collectionMap;

	@Autowired
	private ApplicationContext applicationContext;

	public static void main(String[] args) {
		SpringApplication.run(SpringCollectionMapApp.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		collectionMap.getMap().forEach((k, v) -> System.out.println(k + " -> " + v));

		System.out.println("========================================================");

		RoytutsInfoMap roytutsInfoMap = applicationContext.getBean(RoytutsInfoMap.class);

		roytutsInfoMap.getMap().forEach((k, v) -> System.out.println(k + " -> " + v));
	}

}

Testing the Application

Executing the above main class you will see the following output:

site -> https://roytuts.com
author -> Soumitra
about -> https://roytuts.com/about
facebook -> https://www.facebook.com/roytuts2014
twitter -> https://twitter.com/roytuts
youtube -> https://www.youtube.com/channel/UCMysotNzptWegWBSY9lox_g
ello -> https://ello.co/soumitrajuster
linkedin -> https://www.linkedin.com/in/soumitra-sarkar-80ba0328/
========================================================
site -> https://roytuts.com
author -> Soumitra
about -> https://roytuts.com/about
facebook -> https://www.facebook.com/roytuts2014
twitter -> https://twitter.com/roytuts
youtube -> https://www.youtube.com/channel/UCMysotNzptWegWBSY9lox_g
ello -> https://ello.co/soumitrajuster
linkedin -> https://www.linkedin.com/in/soumitra-sarkar-80ba0328/

That’s all about how to work with collection type map in Spring applications.

Source Code

Download

Leave a Reply

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