- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Spring Boot YAML configuration for a list of strings
I am trying to load an array of strings from the application.yml file. This is the config:
This is the class fragment:
There are other configurations in the same class that loads just fine. There are no tabs in my YAML file. Still, I get the following exception:
- spring-boot
- configuration
10 Answers 10
use comma separated values in application.yml
java code for access
It is working ;)
- I was hoping this would work in Dropwizard too :'( thanks though! – RST May 16, 2018 at 18:33
- 9 In my own tests, this is equivalent to ".DS_Store, .hg" but not ".DS_Store", ".hg" - the latter fails with "org.yaml.snakeyaml.parser.ParserException: while parsing a block mapping". So what you're actually doing here is providing the property as a single comma-separated string (which Spring then splits into an array or list) instead of a YAML array. This "works" but doesn't answer the original question. I have yet to find a way to parse a YAML array in a @Value annotated bean property. – Zirzirikos Mar 13, 2019 at 12:42
- List<String> rather than String[] works as well – Prectron Dec 9, 2022 at 20:06
My guess is, that the @Value can not cope with "complex" types. You can go with a prop class like this:
Please note: This code is Groovy - not Java - to keep the example short! See the comments for tips how to adopt.
See the complete example https://github.com/christoph-frick/so-springboot-yaml-string-list

- 2 You can bind a comma-separated with @Value (as long as a converter is registered, which it will be in Spring Boot I think). – Dave Syer Nov 3, 2014 at 8:29
- @Bahadır i tried this code here and it works. @ComponentScan and friends picks this up? – cfrick Nov 4, 2014 at 22:45
- 2 It is picking up string settings but not List<String> settings – Bahadır Yağan Nov 5, 2014 at 12:05
- 3 There must also be a getter defined for the property. – OrangeDog Feb 10, 2016 at 17:56
- 2 This looks like it is a limitation with the spring boot processes that annotation - github.com/spring-projects/spring-boot/issues/501 – wontondon Sep 19, 2016 at 15:39
From the Spring Boot docs:
- https://docs.spring.io/spring-boot/docs/3.0.x/reference/html/features.html#features.external-config (3.0.x)
- https://docs.spring.io/spring-boot/docs/2.7.x/reference/html/features.html#features.external-config (2.7.x)
YAML lists are represented as property keys with [index] dereferencers, for example this YAML:
Would be transformed into these properties:
To bind to properties like that using the Spring DataBinder utilities (which is what @ConfigurationProperties does) you need to have a property in the target bean of type java.util.List and you either need to provide a setter, or initialize it with a mutable value, e.g. this will bind to the properties above. Here is what the question's code would look like.
( Note : The example below only works on Spring Boot 3.0 and greater. Previous versions require the @ConstructorBinding annotation to be present to not throw exceptions when this object is being constructed.)
- 4 This should be working, BTW getXxx() is necessary for it to work, and must use a List , not Set . – Eric Nov 28, 2017 at 3:15
- In the yaml, the list of values for the ArrayList can be a comma delimited list. In my case, I have many values, so a compact list is cleaner than an item per line. So in the example, you can do servers: dev.bar.com, foo.bar.com – Mr. Lee Jul 29, 2019 at 21:08
- 1 Could the yaml be loaded from a properties file like this: servers: ${my.servers} ? To get my.servers[0] and my.servers[1] into the yaml? I'm trying to have stage dependent configurations – ochs.tobi Jul 28, 2020 at 7:58
In addition to Ahmet's answer you can add line breaks to the coma separated string using > symbol.
application.yml :
Java code :

- This works well as long as you don't have any more commas (,) in your strings. – Valentin Despa Jan 8, 2020 at 12:58
- 1 This doesn't work to read properties as arraylist. It reads them as single String. – ssbh May 15, 2020 at 20:12
Well, the only thing I can make it work is like so:
And dont forget the @Configuration above your class....
Without the "," separation, no such luck...
Works too (boot 1.5.8 versie)
- I prefer the first version with > though. If you put comment (e.g. after every line) IDE (IntelliJ) won't highlight the comment it in the first case but highlights it in the second case. It seems like it is supported to put the comment in the second case but it is not. The parser fails in both cases if the comment is there (spring-boot 2.2.10). – Jan Tomášek May 6, 2021 at 20:01
In my case, this was a syntax issue in the .yml file. I had:
and the list in my .yml file:
was not reading into the @Value -annotated field. When I changed the syntax in the .yml file to:
it worked fine.

- 3 Trying this on spring-boot 1.5 this does not work. You need a colon after bootstrap-servers – Taugenichts Jul 10, 2019 at 22:16
- Using spring boot 2.x, the list has a single element of all the values with space separated. – Paramesh Korrakuti Sep 25, 2022 at 10:44
- 1 @Taugenichts You're correct a colon is missing. bootstrap-servers: > – Gagan Oct 20, 2022 at 12:59
There is lot more you can play with spring spEL.

Ahmet's answer provides on how to assign the comma separated values to String array.
To use the above configuration in different classes you might need to create getters/setters for this.. But if you would like to load this configuration once and keep using this as a bean with Autowired annotation, here is the how I accomplished:
In ConfigProvider.java
In outside classes:
you can use the same list everywhere else by autowiring.
- 1 That works. In my case though the application failed, unless I add @Configuration at the beginning of the class in ConfigProvider.java . Otherwise i got Source required a bean of type 'java.util.List' that could not be found. – Diana Jun 24, 2019 at 12:27
Configuration in yaml file:
In spring component:
This worked fine for me.

- 1 How is this different form Ahmet's answer? stackoverflow.com/a/41462567/2065796 – Sasha Shpota Nov 23, 2018 at 16:00
- 2 Answer already provided. Answering just for the sake of points doesn't add value – Deepak Dec 13, 2018 at 8:43
Not the answer you're looking for? Browse other questions tagged spring-boot configuration yaml or ask your own question .
- The Overflow Blog
- Can Stack Overflow save the day?
- Let’s talk large language models (Ep. 546)
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- Temporary policy: ChatGPT is banned
Hot Network Questions
- clarification of u-substitution theorem
- Is it a valid chemical?
- I contacted a professor for PhD supervision, and he replied that he would retire in two years. How should I respond?
- ??? Adjectives?
- Is an electron more stable than a proton/neutron?
- Under what circumstances does f/22 cause diffraction?
- when did command line applications start using "-h" as a "standard" way to print "help"?
- Are there any other examples where "weak" and "strong" are confused in mathematics?
- Is reading multiple buttons presses with ATtiny analog input a reliable method?
- Why is there no video of the drone propellor strike by Russia
- "Mainframe" with Z80
- A challenge between Sandman and Lucifer Morningstar
- What is the last integer in this sequence?
- Does a purely accidental act preclude civil liability for its resulting damages?
- are there any non conventional sources of law?
- Did MS-DOS have any support for multithreading?
- Did I give the right advice to my father about his 401k being down?
- How much technical / debugging help should I expect my advisor to provide?
- Struggling with participle phrases - adjectival vs adverbial
- How are the banks behind high yield savings accounts able to pay such high rates?
- What is the difference between \bool_if_p:N and \bool_if:NTF
- How does the brake fluid return to reservoir in Disc Brakes after brake pedal is released?
- How can I restore my default .bashrc file again?
- What lentils did I buy?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Home » Spring » YAML to Java List of Objects in Spring Boot
YAML to Java List of Objects in Spring Boot
Examples of reading a list or a collection of properties from a YAML file or an application properties files into Java List of Objects in Spring Boot.
Tutorial Contents
This quick tutorial covers examples of reading lists or collections from a YAML file or a Properties file into Java List or Set instances in a Spring Boot application.
The @ConfigurationProperties annotation in Spring Boot maps the YAML or Properties-based configurations, including collections, into Java bean instances and is very flexible. We recommend reading Using @ConfigurationProperties in Spring Boot to learn more about the annotation.
Lists in YAML or Properties Files
The YAML and Properties files help store and transfer data and data structures, and we mainly use them to keep our Application Configurations. They both allow human-readable syntax for storing different types of data structures like key and value pairs, maps, simple collections, and collections of other objects.
Before we begin, let’s look at the different types of collections or lists that can appear in the YAML file. The YAML
Simple Collections in YAML
The YAML file defines a list of 4 elements. We. can also specify a similar configuration in a Properties file instead.
Collection of Maps in YAML
Here is a YAML list of Maps.
Each element of the ‘ listOfMaps ‘ collection is a Map, a collection of key and value pairs.
Collection of Objects in YAML
Alternatively, a YAML collection may contain objects.
The elements of this YAML collection contain the other fields. Thus, it represents a List of Objects.
This section summarised some simple and complex application configurations we can put in Spring Boot’s application YAML or Properties file. The following sections will practically show how to use Spring’s @PropertiesConfiguration to map the YAML or Properties Collections into Java Collections like List, Set, Map, etc.
YAML to Plain Java List
Consider our YAML file has a List of simple elements, as shown in the following snippet.
To map this YAML collection, we will use the @ConfigurationProperties annotation with a prefix of “ config “. Because of the prefix, Spring will only map the configurations nested within the “ config ” element.
Here, we used an object of Java List of Strings with the same name as the properties root in the YAML or Properties file. As we read the configurations nested within the “ config “, our variable name is “ env “.
Starting the application and printing the variable on the startup shows that we correctly mapped the YAML collection into a Java Collection.
YAML to Java List of Map
As we saw earlier, elements of a collection in YAML or Properties files can be a group of unrelated fields. For example, the Collection in the following YAML file contains random fields. We can read such YAML collections into a collection of Java Maps.
To do so, we will create an object of List of Map type in our @ConfigurationProperties class.
Launching the application and printing the miscellaneous object on the startup shows that we correctly read the Collection of maps from the YAML file.
YAML to Java List of Object
Alternatively, the collection elements in a YAML or Properties file can have a fixed set of fields, making it a collection of the same object instances. For example, the Collection in the following YAML has two elements containing the same fields representing a list of different services.
To map this Collection in Java objects, we will first create a class, Service, having the name and url fields. In the @ConfigurationProperties class, we will define a member of the Collection of the service type.
Printing the Collection upon startup correctly shows that the Collection of the objects is correctly injected in the Java objects.
YAML to Java Set
We mapped the collections from YAML or Properties files in previous examples into Java List instances. However, we can also map them into other collection objects in Java, for example, a Set.
The advantage of using Set over a Java List is that Set implementations are unique. Thus it will remove all the duplicates from the List.
Example of Mapping a collection of objects from YAML into a Java Set of objects
Compared to the example from the previous section, the only difference is the type of services variable, which is now a Set.
As expected, we have correctly mapped the List in the YAML into a Java Set instance.
This quick tutorial illustrated different ways of mapping YAML or Properties configurations into Java List or Set instances. We understood various forms of YAML or Properties configurations and collections of configurations.
Then we explored examples using @ConfigurationProperties to map these configuration lists into plain Java List, List of Map, or List of Java Objects. In the last section, we understood that we could also bind YAML or Properties configurations in Java Set. By doing so, we always get a list of unique elements.
You can refer to our GitHub Repository for the complete source code of the examples used in this tutorial .
More like this:
- Using @ConfigurationProperties in Spring Boot
- YAML to Map with Spring Boot
- Reading Nested Properties in Spring Boot
- Validations with @ConfigurationProperties in Spring Boot
Instantly share code, notes, and snippets.
caprica / application-properties.yaml
24. Externalized Configuration
Spring Boot allows you to externalize your configuration so you can work with the same application code in different environments. You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration. Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects.
Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values, properties are considered in the the following order:
- Command line arguments.
- JNDI attributes from java:comp/env .
- Java System properties ( System.getProperties() ).
- OS environment variables.
- A RandomValuePropertySource that only has properties in random.* .
- Profile-specific application properties outside of your packaged jar ( application-{profile}.properties and YAML variants)
- Profile-specific application properties packaged inside your jar ( application-{profile}.properties and YAML variants)
- Application properties outside of your packaged jar ( application.properties and YAML variants).
- Application properties packaged inside your jar ( application.properties and YAML variants).
- @PropertySource annotations on your @Configuration classes.
- Default properties (specified using SpringApplication.setDefaultProperties ).
To provide a concrete example, suppose you develop a @Component that uses a name property:
You can bundle an application.properties inside your jar that provides a sensible default name . When running in production, an application.properties can be provided outside of your jar that overrides name ; and for one-off testing, you can launch with a specific command line switch (e.g. java -jar app.jar --name="Spring" ).
24.1 Configuring random values
The RandomValuePropertySource is useful for injecting random values (e.g. into secrets or test cases). It can produce integers, longs or strings, e.g.
The random.int* syntax is OPEN value (,max) CLOSE where the OPEN,CLOSE are any character and value,max are integers. If max is provided then value is the minimum value and max is the maximum (exclusive).
24.2 Accessing command line properties
By default SpringApplication will convert any command line option arguments (starting with ‘--’, e.g. --server.port=9000 ) to a property and add it to the Spring Environment . As mentioned above, command line properties always take precedence over other property sources.
If you don’t want command line properties to be added to the Environment you can disable them using SpringApplication.setAddCommandLineProperties(false) .
24.3 Application property files
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment :
- A /config subdir of the current directory.
- The current directory
- A classpath /config package
- The classpath root
The list is ordered by precedence (locations higher in the list override lower items).
If you don’t like application.properties as the configuration file name you can switch to another by specifying a spring.config.name environment property. You can also refer to an explicit location using the spring.config.location environment property (comma-separated list of directory locations, or file paths).
If spring.config.location contains directories (as opposed to files) they should end in / (and will be appended with the names generated from spring.config.name before being loaded). The default search path classpath:,classpath:/config,file:,file:config/ is always used, irrespective of the value of spring.config.location . In that way you can set up default values for your application in application.properties (or whatever other basename you choose with spring.config.name ) and override it at runtime with a different file, keeping the defaults.
24.4 Profile-specific properties
In addition to application.properties files, profile-specific properties can also be defined using the naming convention application-{profile}.properties . The Environment has a set of default profiles (by default [default] ) which are used if no active profiels are set (i.e. if no profiles are explicitly activated then properties from application-default.properties are loaded).
Profile specific properties are loaded from the same locations as standard application.properties , with profile-specific files always overriding the non-specific ones irrespective of whether the profile-specific files are inside or outside your packaged jar.

24.5 Placeholders in properties
The values in application.properties are filtered through the existing Environment when they are used so you can refer back to previously defined values (e.g. from System properties).
24.6 Using YAML instead of Properties
YAML is a superset of JSON, and as such is a very convenient format for specifying hierarchical configuration data. The SpringApplication class will automatically support YAML as an alternative to properties whenever you have the SnakeYAML library on your classpath.
24.6.1 Loading YAML
Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean will load YAML as Properties and the YamlMapFactoryBean will load YAML as a Map .
For example, the following YAML document:
Would be transformed into these properties:
YAML lists are represented as property keys with [index] dereferencers, for example this YAML:
To bind to properties like that using the Spring DataBinder utilities (which is what @ConfigurationProperties does) you need to have a property in the target bean of type java.util.List (or Set ) and you either need to provide a setter, or initialize it with a mutable value, e.g. this will bind to the properties above
24.6.2 Exposing YAML as properties in the Spring Environment
The YamlPropertySourceLoader class can be used to expose YAML as a PropertySource in the Spring Environment . This allows you to use the familiar @Value annotation with placeholders syntax to access YAML properties.
24.6.3 Multi-profile YAML documents
You can specify multiple profile-specific YAML documents in a single file by using a spring.profiles key to indicate when the document applies. For example:
In the example above, the server.address property will be 127.0.0.1 if the development profile is active. If the development and production profiles are not enabled, then the value for the property will be 192.168.1.100 .
The default profiles are activated if none are explicitly active when the application context starts. So in this YAML we set a value for security.user.password that is only available in the "default" profile:
whereas in this example, the password is always set because it isn’t attached to any profile, and it would have to be explicitly reset in all other profiles as necessary:
24.6.4 YAML shortcomings
YAML files can’t be loaded via the @PropertySource annotation. So in the case that you need to load values that way, you need to use a properties file.
24.7 Typesafe Configuration Properties
Using the @Value("${property}") annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that allows strongly typed beans to govern and validate the configuration of your application. For example:
When the @EnableConfigurationProperties annotation is applied to your @Configuration , any beans annotated with @ConfigurationProperties will be automatically configured from the Environment properties. This style of configuration works particularly well with the SpringApplication external YAML configuration:
To work with @ConfigurationProperties beans you can just inject them in the same way as any other bean.
It is also possible to shortcut the registration of @ConfigurationProperties bean definitions by simply listing the properties classes directly in the @EnableConfigurationProperties annotation:
24.7.1 Third-party configuration
As well as using @ConfigurationProperties to annotate a class, you can also use it on @Bean methods. This can be particularly useful when you want to bind properties to third-party components that are outside of your control.
To configure a bean from the Environment properties, add @ConfigurationProperties to its bean registration:
Any property defined with the foo prefix will be mapped onto that FooComponent bean in a similar manner as the ConnectionSettings example above.
24.7.2 Relaxed binding
Spring Boot uses some relaxed rules for binding Environment properties to @ConfigurationProperties beans, so there doesn’t need to be an exact match between the Environment property name and the bean property name. Common examples where this is useful include dashed separated (e.g. context-path binds to contextPath ), and capitalized (e.g. PORT binds to port ) environment properties.
For example, given the following @ConfigurationProperties class:
The following properties names can all be used:
Table 24.1. relaxed binding
Spring will attempt to coerce the external application properties to the right type when it binds to the @ConfigurationProperties beans. If you need custom type conversion you can provide a ConversionService bean (with bean id conversionService ) or custom property editors (via a CustomEditorConfigurer bean).
24.7.3 @ConfigurationProperties Validation
Spring Boot will attempt to validate external configuration, by default using JSR-303 (if it is on the classpath). You can simply add JSR-303 javax.validation constraint annotations to your @ConfigurationProperties class:
You can also add a custom Spring Validator by creating a bean definition called configurationPropertiesValidator .

Injecting List with Spring from yaml
In my recent project, I need to fill a list from configuration file. With my old habits I just tried to use @Value annotation and my code just broke. Here is what I’ve tried first:
application.yaml:
AppRunner.java:
However, it just exploded like below:
After that, I used a workaround for this problem and solve the issue with below annotation style on segmentList and application.yaml:
I was basically, splitting a String with comma. It seems fine when I run the application. However, when I run my unit tests I get below error:
I’ve looked at a lot of annotation like @TestPropertySource and tried a lot of methods like injecting PropertyPlaceHolder to my test classes to run unit tests with this way but couldn’t manage it. The application context doesn’t aware of my properties because different application context is created when I run tests. At the end, I found this issue on Spring’s Jira system. That was the same issue I had and it guided me to @ConfigurationProperties annotation. And fortunately, I was using Spring Boot and already have this annotation in my path. With this guidance I add a new configuration class, changed application.yaml to list style again and get my list from configurations with the help of @EnableConfigurationProperties annotation at injection:
Config class:
Runner class:
When I dig into a little bit, I found that @ConfigurationProperties can do more. Here is a nice little blog post about how to use it.
I simulated my steps in different commits at this repository . You can check whole working code and not working codes from there.
Developers Rock!!!
Share this:
1 response to injecting list with spring from yaml.
I came here with the same issue…thank you for this post
Leave a Reply Cancel reply
Fill in your details below or click an icon to log in:
You are commenting using your WordPress.com account. ( Log Out / Change )
You are commenting using your Twitter account. ( Log Out / Change )
You are commenting using your Facebook account. ( Log Out / Change )
Connecting to %s
Notify me of new comments via email.
Notify me of new posts via email.
- Search for:
Recent Posts
- How to generate self-signed X.509 certificates for local development (Nginx)
- Gpg – can’t connect to `/home/${USER)/.gnupg/S.gpg-agent’: No such file or directory
- Oracle Null Safe Comparison (Spoiler alert: SYS_OP_MAP_NONNULL)
- Git – Moving folders with history and all related branches
- Installation of Oracle SQL Developer to Ubuntu
- Shell Script
- 357,488 hits
- October 2017
- February 2016
- December 2014
- August 2014
- February 2014
- January 2014
- December 2013
- August 2013
- February 2013
- January 2013
- December 2012
- November 2012
- October 2012
- A. Fuat Sungur's Blog
- Emrah Mete's Blog
- Emre Baransel's Blog
- Gürcan Orhan's Blog
- H.Tonguç Yılmaz's Blog
- Harun Küçükşabanoğlu's Blog
- Hüsnü Şensoy's Blog
- Jonathan Lewis's Blog
- Mustafa Taşdemir's Blog
- Tom Kyte's Blog
- Yasa Akbulut's Blog
- Zafer Cakmak's Blog
- Entries feed
- Comments feed
- WordPress.com

- Already have a WordPress.com account? Log in now.
- Follow Following
- Copy shortlink
- Report this content
- View post in Reader
- Manage subscriptions
- Collapse this bar
Read values from YAML file in Spring Boot
This post will discuss how to read values defined in the application.yml file in a Spring Boot application.
In a Spring Boot application, we can use properties files, YAML files, environment variables, and command-line arguments to externalize our configuration. This is useful while working with the same application code in different environments. This post will discuss how to read values defined in the application.yml file.
application.yml
Following is a simple YAML file containing demo.environment and demo.hosts properties. The demo.environment is a string type, and demo.hosts is a collection of String.
Spring Boot provides a method of working with properties that lets strongly typed beans govern and validate the configuration of your application, as shown in the following example:
Config.java
The Following configuration class uses @ConfigurationProperties annotation to bind and validate the external configuration to this class.
Now that all properties are loaded from a YAML file, we create an object of the Config class and display the properties using the CommandLineRunner .
Output: {prod, [https://www.example1.com, https://www.example2.com]}
That’s all about reading values from the YAML file in Spring Boot.
Rate this post
Average rating 4.63 /5. Vote count: 8
No votes so far! Be the first to rate this post.
We are sorry that this post was not useful for you!
Tell us how we can improve this post?
Social Network for Programmers and Developers
We're sorry but this website doesn't work properly without javascript enabled. please enable it to continue..

IMAGES
VIDEO
COMMENTS
use comma separated values in application.yml ignoreFilenames: .DS_Store, .hg. java code for access @Value("${ignoreFilenames}") String[] ignoreFilenames.
YAML to List of Objects in Spring Boot · yamlconfig: list: - item1 - item2 - item3 - item4 · yamlconfig. · application: profiles: - dev - test -
The @ConfigurationProperties annotation in Spring Boot maps the YAML or Properties-based configurations, including collections, into Java bean instances and
For a property in a Spring component like this: #. # @Value("${property.name}"). # private List<String> values;. #. # Spring will fail to start up with a
As I remember, we configured the list with a comma-delimited string and tokenized the string into a list. We'd definitely prefer that the standard YAML syntax
Property values can be injected directly into your beans by using the @Value annotation, accessed through Spring's Environment abstraction, or be bound to
You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration. Property values can be injected
In my recent project, I need to fill a list from configuration file. With my old habits I just tried to use @Value annotation and my code
In a Spring Boot application, we can use properties files, YAML files, environment variables, and command-line arguments to externalize our configuration. This
In this tutorial, we learn how to map YAML lists into Java Lists. We also checked how to bind complex lists to custom POJOs.