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.
# @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):
<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_HOST → dbHost).
Reading values
Section titled “Reading values”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` aroundString 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:
mvn -q packagevarlock run -- java -jar target/myapp.jarWith Spring Boot, wrap the usual run goal (or the packaged jar) the same way:
varlock run -- ./mvnw spring-boot:run# or, after `./mvnw -q package`:varlock run -- java -jar target/myapp.jarload() throws a clear error if __VARLOCK_ENV is missing (e.g. you forgot varlock run) or if a required key is absent.
Sharing one instance
Section titled “Sharing one instance”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:
@Configurationpublic class EnvConfig { @Bean public Env env() { return Env.load(); // call once at startup }}
@Servicepublic 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)