在SpringBoot中读取环境变量

Mic*_*zyk 20 java spring environment-variables spring-boot

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

String foo = System.getenv("bar");
Run Code Online (Sandbox Code Playgroud)

是否可以使用@Value注释来完成?

g00*_*00b 31

引用文档:

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

因此,由于Spring引导允许您使用环境变量进行配置,并且由于Spring引导也允许您使用@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
    }
}
Run Code Online (Sandbox Code Playgroud)


Rla*_*que 22

您可以使用@Value注释来执行此操作:

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

如果找不到,您还可以使用冒号来提供默认值:

@Value("${bar:default_value}")
private String myVariable;
Run Code Online (Sandbox Code Playgroud)

  • 仅适用于已初始化的组件,不能在静态主函数的主类中工作。 (2认同)

nob*_*bar 10

以下是用于访问名为 的系统环境变量的三种“占位符”语法MY_SECRET

@Value("${MY_SECRET:aDefaultValue}")
private String s1;

@Value("#{environment.MY_SECRET}")
private String s2;

@Value("${myApp.mySecretIndirect:aDefaultValue}") // via application property
private String s3;
Run Code Online (Sandbox Code Playgroud)

在第三种情况下,占位符引用了一个应用程序属性,该属性已从属性文件中的系统环境初始化:

myApp.mySecretIndirect=${MY_SECRET:aDefaultValue}
Run Code Online (Sandbox Code Playgroud)

为了@Value工作,它必须在 live @Component(或类似的)中使用。如果您希望它在单元测试期间工作,还有额外的 gochas - 请参阅我对为什么我的 Spring @Autowired 字段为空的回答

  • 请注意使用“environment.”时不同的标点符号“#{”与“${”。 (3认同)

Sai*_*pta 6

或者,您可以使用该org.springframework.core.env.Environment接口访问环境变量:

@Autowired
private Environment env;

...

System.out.println(env.getProperty("bar"));
Run Code Online (Sandbox Code Playgroud)

阅读更多...

  • 不适用于`@SpringBootApplication`类的主要静态函数。仅适用于已初始化的 Spring 组件。 (3认同)