Loading List from Properties file with spring @Value
This example shows you how to load a list from a properties file using the @Value
annotation. In this tutorial we’ll be using the comma as a separator. But you can use any delimiter you want.
Spring @Value Loading List from Properties
We can load a list from a properties file by annotating the field with the @Value
annotation. And providing the property name of the resource. The PropertySourcesPlaceholderConfigurer
is used to resolve the ${} in the expression. We can manipulate the property with the split()
method.
package com.memorynotfound.spring.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import java.util.List;
@Configuration
@PropertySource(value="classpath:application.properties")
public class AppConfig {
@Value("#{'${planets.names}'.split(',')}")
private List<String> planets;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
public List<String> getPlanets() {
return planets;
}
}
Properties File
We registered one property planets.names in the application.properties file. This file is located on the class path.
planets.names=Sun,Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune
Running The Application
We bootstrap the application and retrieve the AppConfig
class. Afterwards we print the values to the console.
package com.memorynotfound.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Run {
public static void main(String... args){
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
AppConfig appConfig = context.getBean(AppConfig.class);
System.out.println("planets: " + appConfig.getPlanets());
}
}
Output
The previous code will produce the following output.
Planets: [Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune]
How to handle property file not being populated
Make sure your application.properties file resides on the classpath. When using Maven, you can add it to
src/main/resources
folder.