Spring Boot:从YAML文件加载@Value [英] Spring Boot: Load @Value from YAML file

查看:55
本文介绍了Spring Boot:从YAML文件加载@Value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 .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 Environment:

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

这篇关于Spring Boot:从YAML文件加载@Value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆