Thomas Schmidt Thomas Schmidt - 1 month ago 55
Java Question

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.XXX
or
hibernate.XXX
.

Answer

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

Comments