
Share:
)
Diana is a developer advocate at Vonage. She likes eating fresh oysters.
Working with Environment Variables in Java
Time to read: 5 minutes
Introduction
Environment variables (sometimes called "env vars") are variables that you store outside your program, which can affect how it runs. You can later use that value to change how programs, applications, and services behave. Applications treat environment variables as fixed values during execution rather than mutable variables (a value that can change). They’re most useful for values you would normally hard-code but should keep out of your code, either because they change between environments or because they’re sensitive, like API keys or passwords. This keeps your code portable, easier to manage, and protects secrets in less secure environments, such as development or testing.
In this blog post, you’ll learn what environment variables are, why they’re important in Java applications, common use cases, and how to set and access them across different environments.
Prerequisites
- Basic knowledge of Java
- An IDE like IntelliJ IDEA or Eclipse
- A Vonage account
Vonage API Account
To complete this tutorial, you will need a Vonage API account. If you don’t have one already, you can sign up today and start building with free credit. Once you have an account, you can find your API Key and API Secret at the top of the Vonage API Dashboard.
Use Cases
Common ways to use environment variables include:
store API keys, passwords, and tokens securely outside code.
switch configurations between development, testing, staging, and production.
run the same code across machines or containers without changes.
define variables like
PATH
orJAVA_HOME
.
Storing API Keys, Passwords, and Tokens
How It Works
Sensitive information such as API keys, database passwords, or authentication tokens can be stored in environment variables (e.g., API_KEY
or DB_PASSWORD
).
Benefits
Keeping secrets out of the source code lowers security risks and prevents accidental leaks in version control. It also makes it easier to rotate keys or passwords since you can just edit a single file.
Implementation Example
In Java, a Vonage API key can be stored as an environment variable, such as VONAGE_API_KEY
. You’d access it in code with System.getenv("VONAGE_API_KEY")
, ensuring the key isn’t embedded directly in the application.
Switching Configurations Between Environments
How It Works
Environment variables, such as ENV_MODE
or APP_ENV
, can indicate whether the application is running in development, testing, staging, or production environments.
Benefits
This allows applications to adjust their behavior based on context automatically. For example, in development mode, you might enable verbose logging, while in production, those logs are minimized for performance.
Implementation Example
A Java application might check System.getenv("ENV_MODE")
to choose the correct database connection string or to enable/disable debugging tools depending on the environment.
Running the Same Code Across Machines or Containers
How It Works
By keeping environment variables outside of the code, the same codebase can be deployed across different machines, servers, or containers without modification.
Benefits
This makes applications easier to move and scale, particularly in containerized setups like Docker or Kubernetes, since you only need to adjust environment variable values without touching the source code.
Implementation Example
A containerized Java application might define environment variables for database credentials and service URLs. Regardless of whether the container runs locally or in production, the same code works because it reads from the environment.
Defining Path Variables
How It Works
Environment variables such as PATH
or JAVA_HOME
specify system-level locations for executables, libraries, or runtime environments.
Benefits
This allows tools and applications to run consistently without hardcoding file locations. It’s particularly useful when running software on multiple platforms, each with different directory structures.
Implementation Example
In Java, setting JAVA_HOME
makes sure the application always knows where to find the JDK. By reading paths from environment variables, developers avoid platform-specific issues and make their applications more portable.
How to Use Environment Variables
To use environment variables, you first define them in your system or a configuration file, then access their values from your application at runtime.
Setting Environment Variables
As best practice, set environment variables in your operating system before starting your Java application. This can be done in the command line or directly within a .env file.
Set Environment Variables Before Running Java Application
The most common approach is to set environment variables in your operating system before starting your Java application. This can be done in the command line or through scripts.
For example, in a Unix environment, you can set an environment variable in the terminal like this:
In Windows Command Prompt, it would be:
set MY_VAR=some value
Set for Sub-Processes
If you need to set environment variables for subprocesses started from your Java application (and not for the Java process itself), you can use the ProcessBuilder class:
ProcessBuilder processBuilder = new ProcessBuilder();
Map<String, String> env = processBuilder.environment();
env.put("MY_VAR", "some value");
Process process = processBuilder.start();
Set Environment Variables in IDE
If you are using an Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse, you can set environment variables in the configuration settings of your application.
Set Environment Variables in Build Tools
When using build tools like Maven or Gradle, you can configure environment variables in the build scripts or configuration files.
Loading Configurations From a File
Since java.util.Properties
implements the Map interface, you can load any file that maps key-value pairs like so, irrespective of its file extension:
var props = new Properties();
var envFile = Paths.get("/path/to/MyEnvConfig.env");
try (var inputStream = Files.newInputStream(envFile)) {
props.load(inputStream);
}
String apiKey = props.get("VONAGE_API_KEY");
String apiSecret = props.get("VONAGE_API_SECRET");
Getting Environmental Variables
Accessing environment variables in Java is straightforward and can be done using the System
class, which is provided by the standard Java library. Here's a simple guide on how to do it:
Get a Single Environment Variable: Use the System.getenv(String name)
method to retrieve the value of a specific environment variable. For example, to access an environment variable named API_KEY
, you would use:
String apiKey = System.getenv("API_KEY");
Check for Null Values: It's a good practice to check if the environment variable is null (i.e., not set) to avoid potential NullPointerExceptions
. For example:
String apiKey = Optional.ofNullable(System.getenv("API_KEY")).orElse(otherValue);
Here, otherValue
is the fallback value. If you’d prefer to fail fast when the environment variable is missing, you can throw an exception instead:
Optional.ofNullable(System.getenv("API_KEY")).orElseThrow(() -> new IllegalStateException("API_KEY env var is not defined"));
Get All Environment Variables: To get a Map<String, String>
of all environment variables, use System.getenv()
. This is useful if you want to iterate over all available environment variables. For example:
Map<String, String> envVars = System.getenv();
for (String envName : envVars.keySet()) {
System.out.format("%s=%s%n", envName, envVars.get(envName));`
}
Alternatively, this can be written in one line:
System.getenv().forEach((k, v) -> System.out.println(k+"="+v));
Share Your Best Practices
Getting and setting environment variables is an essential part of creating production software. If you’ve reached the end of this article, you’re now familiar with what environment variables are, use cases, how to get and set environment variables, and using .env files in Java. We always welcome community involvement. Please feel free to join us on GitHub and the Vonage Community Slack. Do you have other best practices using environment variables? Please share them and tag me. I'd love to hear about them!