• 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:

Prectron's user avatar

10 Answers 10

use comma separated values in application.yml

java code for access

It is working ;)

Ahmet Vehbi Olgaç's user avatar

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

cfrick's user avatar

From the Spring Boot docs:

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.)

Per Lundberg's user avatar

In addition to Ahmet's answer you can add line breaks to the coma separated string using > symbol.

application.yml :

Java code :

Sasha Shpota's user avatar

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)

Roland Roos's user avatar

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.

Matt Campbell's user avatar

There is lot more you can play with spring spEL.

Vivek Swansi's user avatar

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.

Deepak's user avatar

Configuration in yaml file:

In spring component:

This worked fine for me.

Paramesh Korrakuti's user avatar

Not the answer you're looking for? Browse other questions tagged spring-boot configuration yaml or ask your own question .

Hot Network Questions

spring value annotation list yaml

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 .

amitph

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:

Instantly share code, notes, and snippets.

@caprica

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:

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 :

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 .

spring value annotation list yaml

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.

' src=

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:

Gravatar

You are commenting using your WordPress.com account. (  Log Out  /  Change  )

Twitter picture

You are commenting using your Twitter account. (  Log Out  /  Change  )

 width=

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.

Recent Posts

' src=

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?

guest

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

  1. Spring annotation

    spring value annotation list yaml

  2. Spring @Value Annotation

    spring value annotation list yaml

  3. Spring Boot Annotations

    spring value annotation list yaml

  4. Value Spring: Spring @Value annotation tricks

    spring value annotation list yaml

  5. Difference between @Autowired and @Inject annotation in Spring?

    spring value annotation list yaml

  6. Spring Value Season is Here

    spring value annotation list yaml

VIDEO

  1. LabVIEW: Adding annotation to graph

  2. Tension Spring Value

  3. Lec10-Spring Boot MVC REST Annotations With Examples

  4. Spring Value 23

  5. @Repository Annotation

  6. Introduction to YAML Basics

COMMENTS

  1. Spring Boot YAML configuration for a list of strings

    use comma separated values in application.yml ignoreFilenames: .DS_Store, .hg. java code for access @Value("${ignoreFilenames}") String[] ignoreFilenames.

  2. YAML to List of Objects in Spring Boot

    YAML to List of Objects in Spring Boot · yamlconfig: list: - item1 - item2 - item3 - item4 · yamlconfig. · application: profiles: - dev - test -

  3. YAML to Java List of Objects in Spring Boot

    The @ConfigurationProperties annotation in Spring Boot maps the YAML or Properties-based configurations, including collections, into Java bean instances and

  4. Spring Boot YAML configuration for lists (or arrays) of strings · GitHub

    For a property in a Spring component like this: #. # @Value("${property.name}"). # private List<String> values;. #. # Spring will fail to start up with a

  5. Value annotation should be able to inject List<String> from YAML

    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

  6. 24. Externalized Configuration

    Property values can be injected directly into your beans by using the @Value annotation, accessed through Spring's Environment abstraction, or be bound to

  7. 24. Externalized Configuration

    You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration. Property values can be injected

  8. 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

  9. Read values from YAML file in Spring Boot

    In a Spring Boot application, we can use properties files, YAML files, environment variables, and command-line arguments to externalize our configuration. This

  10. How to Map A YAML List into A List In Spring Boot

    In this tutorial, we learn how to map YAML lists into Java Lists. We also checked how to bind complex lists to custom POJOs.