在 SpringBoot 中读取环境变量

2023-07-14Java开发问题
189

本文介绍了在 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 注释来做到这一点?

Is it possible to do it using @Value annotation?

推荐答案

引用 文档:

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.

例如,以下将给出相同的结果:

For example, 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 中读取环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13