Collection Element List in Spring

With this example I will show you how to inject List Collection in Spring application. The collection type I am going to show you is List or Array. I am going to use Spring Boot framework. I will show you various ways of loading a list of configurable properties in Spring application.

The list of elements you use generally coming from some persistent storage or external services but you may need to configure a list of elements in the properties files for some situations.

For example, the list 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-list</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>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</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 list or array configuration.

Injecting Collection – List

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

Let’s say you have configured the following in your src/main/resources/application.properties file:

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

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

@Value("${roytuts.list}")
private String[] strArray;

So you can easily read those values from the array and process accordingly for your application business requirements.

You can also get the list from the above comma separated elements in the property file configuration in the following way:

@Value("#{'${roytuts.list}'.split(',')}")
private List<String> strList2;

You can also configure the elements in application properties file which can be treated as list:

blog.roytuts.list={java,spring,rest,roytuts2014@gmail.com}

In your Java class you can use the following configuration:

@Value("${blog.roytuts.list}")
private List<String> strList;

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

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

In Java you can create the following configuration class for getting the values as in a list.

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

	private List<String> list;

	public List<String> getList() {
		return list;
	}

	public void setList(List<String> list) {
		this.list = list;
	}

}

Then you can auto-wire the above class file into another class where you want to use:

@Autowired
private RoytutsList roytutsList;

You can also use the traditional approach using the XML configuration file. The following list is declared in the XML config file:

<?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.list.SpringCollectionList">
		
		<!-- results in a list(java.util.List) call -->
		<property name="list">
			<list>
				<value>java</value>
				<value>spring</value>
				<value>rest</value>
				<value>roytuts2014@gmail.com</value>
			</list>
		</property>
	</bean>

</beans>

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

package com.roytuts.spring.collection.list;

import java.util.List;

public class SpringCollectionList {

	private List<String> list;

	public List<String> getList() {
		return list;
	}

	public void setList(List<String> list) {
		this.list = list;
	}

}

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

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

import java.util.Arrays;
import java.util.List;

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

@SpringBootApplication
public class SpringCollectionListApp implements CommandLineRunner {

	@Value("${roytuts.list}")
	private String[] strArray;

	@Value("${blog.roytuts.list}")
	private List<String> strList;

	@Value("#{'${roytuts.list}'.split(',')}")
	private List<String> strList2;

	@Autowired
	private RoytutsList roytutsList;

	@Autowired
	private ApplicationContext applicationContext;

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

	@Override
	public void run(String... args) throws Exception {
		System.out.println("Array of Strings: " + Arrays.toString(strArray));

		System.out.println();

		System.out.println("List of Strings: " + Arrays.toString(strList.toArray()));

		System.out.println();

		System.out.println("List of Strings2: " + Arrays.toString(strList2.toArray()));

		System.out.println();

		System.out.println("List of Configurable Strings: " + Arrays.toString(roytutsList.getList().toArray()));

		System.out.println();

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

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

}

Testing the Application

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

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

List of Strings: [{java, spring, rest, roytuts2014@gmail.com}]

List of Strings2: [java, spring, rest, roytuts2014@gmail.com]

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

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

That’s all about injecting array and list from Spring property files.

Source Code

Download

Leave a Comment