java - 在 Spring Boot 中读取环境变量

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

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

是否可以使用 @Value 注释来做到这一点?

最佳答案

引用 the documentation :

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 从配置中读取一个属性,那么答案是肯定的。


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

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

https://stackoverflow.com/questions/44803211/

相关文章:

spring - 配置多个数据源后无法设置JPA命名策略(Spring 1.4.1/Hibernat

java - SpringBoot - BeanDefinitionOverrideExceptio

spring - Thymeleaf - 使用 PUBLICID "null"请求的不受支持的实体

database - Spring Batch Framework - 自动创建批处理表

java - Spring Security 中的 "principal"是什么?

java - 我无法使用断点进行调试

java - Spring Boot 是否可以使用 JAR 包装来提供 JSP?

java - 为什么 Spring 的 jdbcTemplate.batchUpdate() 这么慢

java - 如何在spring mvc中使用带有freemarker的消息?

java - 使用 restAssured 测试 Spring Boot Rest 应用程序