【问题标题】:How to access environment variables from .properties using java?如何使用 java 从 .properties 访问环境变量?
【发布时间】:2020-06-10 14:51:06
【问题描述】:

我正在使用 java 来实现 AWS SQS。我想要一个 .properties 文件,我想在其中存储和访问 AWS SQS 访问和密钥的环境变量。目前,我的 .properties 文件是:

dev.access.key={$AWS_ACCESS_KEY}
dev.secret.access.key={$AWS_SECRET_ACCESS_KEY}

我访问这些变量的代码是:

String awsAccessKey = properties.getProperty("dev.access.key");
String awsSecretAccessKey = properties.getProperty("dev.secret.access.key");

我已经实例化了属性并且它已经很好地定义了。我可以获得其他属性,但无法访问我需要的环境变量 Access 和 Secret Key。即当前 awsAccessKey、awsSecretAccessKey 都定义为 null。我如何访问这些环境变量的语法可能有问题吗?

【问题讨论】:

  • 你能从同一个文件中读取其他属性吗?
  • 你能打印出所有的属性吗?
  • 我可以读取其他属性,当我将它们全部打印出来时,我会得到所有正确的值。也就是说,所有其他属性都是字符串。只有两个是环境变量。

标签: java environment-variables amazon-sqs application.properties


【解决方案1】:

这可以通过https://github.com/webcompere/lightweight-config实现

您的占位符语法需要稍微改变:

dev.access.key=${AWS_ACCESS_KEY}
dev.secret.access.key=${AWS_SECRET_ACCESS_KEY}

然后你会写:

Properties myProps = ConfigLoader.loadPropertiesFromResource(
    myproperties.properties");

Lightweight Config 还支持文件系统上的属性,而不是类路径上的属性(如上所述),并允许您使用 YML 而不是 .properties 语法。

【讨论】:

    【解决方案2】:

    您可以使用org.apache.commons.text.StringSubstitutor

    import java.util.Properties;
    import org.apache.commons.text.StringSubstitutor;
    
    public class EnvSubst {
        public static void main(String[] args) {
            // For the demo, create a Properties, normally you will read Properties from file
            Properties p = new Properties();
            p.put("tempfolder", "${TEMP}");
    
            System.out.println("path value : " + 
                new StringSubstitutor(System.getenv()).replace(p.get("tempfolder")));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-21
      • 2023-03-28
      • 1970-01-01
      • 2018-02-20
      • 2011-11-23
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 2019-12-30
      相关资源
      最近更新 更多