在SpringBoot中读取环境变量 [英] Read environment variable in SpringBoot

查看:3684
本文介绍了在SpringBoot中读取环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SpringBoot 中读取环境变量的最佳方法是什么?
在Java中,我是使用以下方法完成的:

What is the best way to read environment variables in SpringBoot?
In Java I did it using:

String foo = System.getenv("bar");

是否可以使用@Value注释?

推荐答案

引用

Spring Boot允许您外部化配置,以便可以在不同环境中使用相同的应用程序代码.您可以使用属性文件,YAML文件,环境变量和命令行参数来外部化配置.可以使用@Value批注将属性值直接注入到您的bean中,可以通过Spring的Environment抽象访问,也可以通过@ConfigurationProperties绑定到结构化对象.

Spring Boot allows you to externalize your configuration so you can work with the same application code in different environments. You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration. Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties.

因此,由于Spring Boot允许您使用环境变量进行配置,并且由于Spring Boot还允许您使用@Value从配置中读取属性,因此答案是肯定的.

So, since Spring boot allows you to use environment variables for configuration, and since Spring boot also allows you to use @Value to read a property from the configuration, the answer is yes.

这很容易测试,以下结果将相同:

This can be tested easily, the following will give the same result:

@Component
public class TestRunner implements CommandLineRunner {
    @Value("${bar}")
    private String bar;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public void run(String... strings) throws Exception {
        logger.info("Foo from @Value: {}", bar);
        logger.info("Foo from System.getenv(): {}", System.getenv("bar")); // Same output as line above
    }
}

这篇关于在SpringBoot中读取环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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