Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/34556677/spring-boot-load-value-from-yaml-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...