如何为springboot指定外部YAML配置文件

dwe*_*eeb 3 java spring-boot

我正在尝试传入一个要从 Spring boot 中的自定义配置文件自动装配的值。下面是代码片段:

春季班

@Configuration
public class MyConfig {

    @Value("${BOOTSTRAP_SERVERS}")
    private String bootstrapServers;
Run Code Online (Sandbox Code Playgroud)

myfile.yaml

BOOTSTRAP_SERVERS: 
  10.0.0.12:9092
Run Code Online (Sandbox Code Playgroud)

执行命令

java  -jar app.jar --spring.config.location=/file/path/myfile.yaml
Run Code Online (Sandbox Code Playgroud)

但是,当我输入上述命令时,我收到此错误:

java.lang.IllegalArgumentException:无法解析值“${BOOTSTRAP_SERVERS}”中的占位符“BOOTSTRAP_SERVERS”

为了让它发挥作用,我在这里缺少什么?我打算将应用程序安装在 kubernetes 中,因此我需要能够外部化我的配置。提前致谢。

ben*_*n c 5

显然这是由于无效的路径声明,要配置外部属性/yml 文件,您必须file:使用--spring.config.location.

所以试试这个,

--spring.config.location="file:/path/to/myfile.yaml"
Run Code Online (Sandbox Code Playgroud)

另一种选择是,

-Dspring.config.location="file:/path/to/myfile.yaml"
Run Code Online (Sandbox Code Playgroud)

确保myfile.yaml在目录中。


官方文档:https://docs.spring.io/spring-boot/docs/2.1.9.RELEASE/reference/html/boot-features-external-config.html#boot-features-external-config-application-property - 文件