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)
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 字段为空的回答?
或者,您可以使用该org.springframework.core.env.Environment接口访问环境变量:
@Autowired
private Environment env;
...
System.out.println(env.getProperty("bar"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36356 次 |
| 最近记录: |