Maven
License: MIT
CI Status

asimov/environment

Tiny library to ease the use of environment variables with support for .env files.

Installation

Gradle (Kotlin)

repositories {
    mavenCentral()
}

dependencies {
    implementation("com.nbottarini:asimov-environment:1.0")
}

Gradle (Groovy)

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.nbottarini:asimov-environment:1.0'
}

Maven

<dependency>
    <groupId>com.nbottarini</groupId>
    <artifactId>asimov-environment</artifactId>
    <version>1.0</version>
</dependency>

Usage

val myEnvValue: String? = Environment["my-env-var"]

val myEnvValue: String? = Environment.get("my-env-var")

val myEnvValue: String = Environment.get("my-env-var", "default value")

val myEnvValue: String = Environment.getOrThrow("my-env-var") // Throws IllegalArgumentException if env var is not present

val allEnvVars = Environment.getAll()

.env

You can create a .env file in the project directory to set environment variables for your development environment.

Sample .env file:

VAR1=VALUE1
VAR2=VALUE2

It is recommended to ignore the .env file from git. You can commit a sample .env.dist file with the default environment
variables (without sensitive values like passwords).

The system environment variables takes precedence over .env variables.

By default, the library tries to find the .env file in the working dir and in the parent dirs.

You can specify additional directories to search:

Environment.addSearchPath('./myDir')

Search paths must be configured before accessing any environment variable.

Usage in gradle files

buildscript {
    dependencies {
        classpath("com.nbottarini:asimov-environment:1.0")
    }
}

Environment.addSearchPath(rootProject.projectDir.absolutePath)

project.ext {
    set("JDBC_URL", "jdbc:postgresql://${Environment["DB_HOST"]}:${Environment["DB_PORT"]}/${Environment["DB_NAME"]}")
}

GitHub

View Github