Collection Element Set In Spring

Introduction

Here in this example I am going to show you how to work with collection element set in Spring Boot application. Actually, a set of properties will be injected into a Spring bean. These properties are configurable in the application.properties or XML configuration files. So, you declare set of values in the configuration or properties file and Spring bean pick them up in a Java collection Set.

These configurable values can easily be updated or modified any time without restarting the server. I am going to show how to map a set of configurable values to Java collection Set both from properties and XML configuration files.

Prerequisites

Java 1.8+, maven 3.6.3 – 3.8.2, Spring Boot 2.4.1 – 2.6.1

Project Setup

You can use any tool or IDE to create a maven based project. The following pom.xml file can be used for your maven based project:

<?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-set</artifactId>
	<version>0.0.1-SNAPSHOT</version>

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

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.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

The application.properties file is created under the src/main/resources folder. This properties file can be used to define a set of values which later can be picked up ate Java collection Set in the Spring bean.

roytuts.set1=java,spring,rest,roytuts2014@gmail.com
 
roytuts.set2={java,spring,rest,roytuts2014@gmail.com}
 
site.roytuts.set[0]=java
site.roytuts.set[1]=spring
site.roytuts.set[2]=rest
site.roytuts.set[3]=roytuts2014@gmail.com
site.roytuts.set[4]=rest

You can also notice that I have put duplicate value in the site.roytuts.set[4] and later you will see that this duplicate value does not get stored in the collection Set.

Injecting Values into Set

The default behavior of Spring application when comma (,) separated strings configured are treated as an array of strings.

Let’s say you have defined the following key and comma separated values for the key:

roytuts.set1=java,spring,rest,roytuts2014@gmail.com

The above values can be mapped to a Set in the following ways:

@Value("${roytuts.set1}")
private Set<String> strSet1;

Or

@Value("#{'${roytuts.set1}'.split(',')}")
private Set<String> strSet12;

The another way of configuring set with indices. The index starts at 0. The following configuration is put into the application.properties file:

site.roytuts.set[0]=java
site.roytuts.set[1]=spring
site.roytuts.set[2]=rest
site.roytuts.set[3]=roytuts2014@gmail.com
site.roytuts.set[4]=rest

The above elements can be mapped into the Set in the following way:

@Configuration // Or @Component
@ConfigurationProperties("site.roytuts")
public class RoytutsSet {

	private Set<String> set;

	public Set<String> getSet() {
		return set;
	}

	public void setSet(Set<String> set) {
		this.set = set;
	}

}

Then you have to auto-wire the above class in the caller:

@Autowired
private RoytutsSet roytutsSet;

You can also use the traditional approach using the XML configuration file. The following set is declared in the XML config file (src/main/resources/set.xml):

<?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="springCollectionList"
		class="com.roytuts.spring.collection.set.SpringCollectionSet">
		<property name="set">
			<set>
				<value>java</value>
				<value>spring</value>
				<value>rest</value>
				<value>roytuts2014@gmail.com</value>
			</set>
		</property>
	</bean>

</beans>

The corresponding mapping class you need to create as follows:

public class SpringCollectionSet {

	private Set<String> set;

	public Set<String> getSet() {
		return set;
	}

	public void setSet(Set<String> set) {
		this.set = set;
	}

}

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

@Configuration
@ImportResource("classpath:set.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.

@SpringBootApplication
public class SpringCollectionSetApp implements CommandLineRunner {

	@Value("${roytuts.set1}")
	private Set<String> strSet1;

	@Value("#{'${roytuts.set1}'.split(',')}")
	private Set<String> strSet12;

	@Value("${roytuts.set2}")
	private Set<String> strSet2;

	@Autowired
	private RoytutsSet roytutsSet;

	@Autowired
	private ApplicationContext applicationContext;

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

	@Override
	public void run(String... args) throws Exception {
		System.out.println();

		System.out.println("Set of Strings1: " + Arrays.toString(strSet1.toArray()));

		System.out.println();

		System.out.println("Set of Strings12: " + Arrays.toString(strSet12.toArray()));

		System.out.println();

		System.out.println("Set of Strings2: " + Arrays.toString(strSet2.toArray()));

		System.out.println();

		System.out.println("Set of Configurable Strings: " + Arrays.toString(roytutsSet.getSet().toArray()));

		System.out.println();

		SpringCollectionSet springCollectionList = applicationContext.getBean(SpringCollectionSet.class);

		System.out.println("Set of XML Config Strings: " + Arrays.toString(springCollectionList.getSet().toArray()));
	}

}

Testing the Application

Running the above main class will produce the following output:

Set of Strings1: [java, spring, rest, roytuts2014@gmail.com]

Set of Strings12: [java, spring, rest, roytuts2014@gmail.com]

Set of Strings2: [{java, spring, rest, roytuts2014@gmail.com}]

Set of Configurable Strings: [java, spring, rest, roytuts2014@gmail.com]

Set of XML Config Strings: [java, spring, rest, roytuts2014@gmail.com]

Source Code

Download

Leave a Reply

Your email address will not be published.