Skip to content

Java

To use varlock with Java, install the standalone binary and run your app under varlock run. It loads and validates your env, then injects it into the process.

Add @generateJavaEnv to your schema to generate a small, self-contained class: a typed Env with public final fields, a static load() that parses the injected __VARLOCK_ENV blob, and a SENSITIVE_KEYS constant.

.env.schema
# @generateJavaEnv(path=src/main/java/Env.java)

The file is regenerated automatically on varlock load and varlock run, or explicitly with varlock codegen. Requires Java 17+ and Jackson on the classpath (jackson-databind):

pom.xml (snippet)
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>

Optional package= and class= set the Java package and class name (default: no package, class Env). Field names are camelCase (DB_HOSTdbHost).

Call load() once, then read fields off the object. Required scalars are primitives (long, boolean, …); optional ones are boxed (Long, Boolean, …) and may be null:

Env e = Env.load(); // call once, hold or pass `e` around
String host = e.dbHost; // String (required field)
if (e.dbPort != null) { // Long (optional field)
System.out.println(host + ":" + e.dbPort);
}

Build a jar as usual, then run it under varlock:

Terminal window
mvn -q package
varlock run -- java -jar target/myapp.jar

With Spring Boot, wrap the usual run goal (or the packaged jar) the same way:

Terminal window
varlock run -- ./mvnw spring-boot:run
# or, after `./mvnw -q package`:
varlock run -- java -jar target/myapp.jar

load() throws a clear error if __VARLOCK_ENV is missing (e.g. you forgot varlock run) or if a required key is absent.

Every load() call re-parses the blob. To avoid reloading, bind the loaded instance wherever your app keeps shared config.

Spring: expose it as a @Bean and inject Env where you need it:

@Configuration
public class EnvConfig {
@Bean
public Env env() {
return Env.load(); // call once at startup
}
}
@Service
public class DbService {
private final Env env;
public DbService(Env env) {
this.env = env;
}
public void connect() {
// env.dbHost, env.dbPort, …
}
}

No DI container? A small holder works:

public final class Config {
public static final Env ENV = Env.load();
}
// elsewhere: Config.ENV.dbPort (Long)