Spring Boot:从 YAML 文件加载 @Value

2022-01-14 00:00:00 yaml spring java spring-boot

我需要从 .yml 文件中加载一个属性,该文件包含应用程序可以从中读取文件的文件夹的路径.

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;

用于开发的 .yml 文件位于 src/main/resources/config/application.yml 下,我在生产中使用以下命令运行应用程序,以覆盖开发设置:

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

Spring Boot 文档说:

The Spring Boot documentation says:

SpringApplication 将从以下位置的 application.properties 文件中加载属性并将它们添加到 Spring 环境中:

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

  1. 当前目录的/config 子目录.

  1. A /config subdirectory of the current directory.

当前目录

类路径/config 包

A classpath /config package

类路径根

还有:

您还可以使用 YAML ('.yml') 文件来替代.properties".

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

.yml 文件包含:

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

我的 Application 类被注释为:

@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}"

是否必须使用 YamlPropertySourceLoader 类或添加特殊注解才能在 Spring Boot 中启用对 .yml 的支持?

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

.yml 文件包含一些其他属性,这些属性可以由 Spring Boot 成功加载,例如 dataSource.XXXhibernate.XXX.

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

推荐答案

M.Deinum 是对的,我提供的设置正在运行 - yml 文件缩进错误,因此无法找到该属性.

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

相关文章