Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: Load @Value from YAML file

I need to load a property from a .yml file, which contains the path to a folder where the application can read files from.

I'm using the following code to inject the property:

@Value("${files.upload.baseDir}") private String pathToFileFolder; 

The .yml file for development is located under src/main/resources/config/application.yml, im running the application with the following command in production, to override the development settings:

java -jar app.jar --spring.config.location=/path/to/application-production.yml 

The Spring Boot documentation says:

SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:

  1. A /config subdirectory of the current directory.

  2. The current directory

  3. A classpath /config package

  4. The classpath root

As well as:

You can also use YAML ('.yml') files as an alternative to '.properties'.

The .yml file contains:

{...} files:       upload:         baseDir: /Users/Thomas/Code/IdeaProjects/project1/files {...} 

And my Application class is annotated with:

@SpringBootApplication @EnableCaching 

When I run the application, i get an exception:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'files.upload.baseDir' in string value "${files.upload.baseDir}" 

Do I have to use the YamlPropertySourceLoader class or add a special annotation to enable the support for .yml in Spring Boot?

Edit: The .yml file contains some other properties, which get successfully loaded by Spring Boot like dataSource.XXXor hibernate.XXX.

like image 423
Thomas Schmidt Avatar asked Jan 01 '16 13:01

Thomas Schmidt


People also ask

How do you inject a Map from a YAML file in spring boot?

How to Inject a Map from a YAML File. Spring Boot has taken data externalization to the next level by providing a handy annotation called @ConfigurationProperties. This annotation is introduced to easily inject external properties from configuration files directly into Java objects.

How do I read a yml file value?

Once we have the file edited and saved, we can use Python to read the values stored in the file. Next, we need to load the YAML file using the safe_load function available in the PyYAML package. From the above code, we start by importing the yaml package.


2 Answers

For example: application.yml

key:  name: description here 

Your Class:

@Value("${key.name}") private String abc; 
like image 92
Nick Borges Avatar answered Sep 23 '22 18:09

Nick Borges


M. Deinum is right, the setup i've provided is working - the yml file was indented wrong, so the property couldn't be found.

like image 32
Thomas Schmidt Avatar answered Sep 24 '22 18:09

Thomas Schmidt