简体   繁体   中英

How to access environment variables from .properties using java?

I'm using java to implement AWS SQS. I want to have a.properties file in which I want to store and access an environment variable for an AWS SQS Access and Secret Key. At the moment, my.properties file is:

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

My code to access these variables is:

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

I have already instantiated properties and it's well defined. I'm able to get other properties but unable to access the environment variables Access and Secret Key, which I require. That is currently awsAccessKey, awsSecretAccessKey are defined as null. Is there perhaps something wrong with my syntax of how I'm accessing those environment variables?

This can be achieved with https://github.com/webcompere/lightweight-config

Your placeholder syntax would need to change slightly:

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

Then you'd write:

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

Lightweight Config also supports properties on filesystem, rather than on the classpath (as above) and allows you to use YML instead of the .properties syntax.

You can use 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")));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM