我需要通过环境变量为应用程序提供配置,并提供了以下代码。我有.NET核心背景,习惯于使用Microsoft.Extensions.Configuration名称空间中的工具。
Java中有哪些工具与这些工具大致类似?具体来说,有没有一种方法可以在不显式读取环境变量的情况下填充POJO类?
public class Settings {
private String applicationKey;
public Settings() {
applicationKey = System.getenv("MYAPP_APPLICATION_KEY");
uri = System.getenv("MYAPP_URI");
}
public String getApplicationKey() {
return applicationKey;
}
}发布于 2021-03-29 23:54:44
具体地说,有没有一种方法可以填充POJO类,而不必显式地读取环境变量?
Java本身并没有专门支持您所说的内容,但是有很多库可以提供帮助。例如,如果您使用的是Micronaut,则可以将代码更改为如下所示:
import io.micronaut.context.annotation.Value;
import javax.inject.Singleton;
@Singleton
public class Settings {
// This will automatically be initialized with the value
// of the MYAPP_APPLICATION_KEY OS environment variable
// if this instance is being managed by Micronaut...
@Value("${myapp.application.key")
String applicationKey;
public String getApplicationKey() {
return applicationKey;
}
}https://stackoverflow.com/questions/66857297
复制相似问题