ProcessBuilder Environment Injection

ProcessBuilder.environment() inherits the parent environment and accepts overrides, so a child process receives staged config without editing global state.

JavaConfig Management

Code

snippet
import java.io.IOException;
import java.util.Map;

public class ChildEnvConfig {

    public static void main(String[] args) throws IOException {
        ProcessBuilder builder = new ProcessBuilder("java", "-version");

        // environment() 按需创建子进程环境:默认继承父进程,再追加专属变量
        Map<String, String> env = builder.environment();
        env.put("DEPLOY_ENV", "staging");
        env.put("LOG_LEVEL", "debug");

        // 回读注入的键:写进的是子进程可见的环境映射
        env.entrySet().stream()
                .filter(e -> e.getKey().startsWith("DEPLOY") || e.getKey().startsWith("LOG"))
                .forEach(e -> System.out.println(e.getKey() + "=" + e.getValue()));

        Process child = builder.start();
        System.out.println("exit code: " + child.onExit().join().exitValue()); // 0
    }
}

The sequence that produces output

ProcessBuilder Environment Injection is built around the class ChildEnvConfig.

The pipeline is a stream: source, lazy intermediate steps, one terminal collector.

Watch out for

  • The project needs no addition before the file runs.

Using it

The demo output is labeled (exit code:); each label names the call that printed it.

Key statements

.filter(e -> e.getKey().startsWith("DEPLOY") || e.getKey().startsWith("LOG"))
.forEach(e -> System.out.println(e.getKey() + "=" + e.getValue()));

Interactive Tools for This Topic

FAQ

What does ProcessBuilder Environment Injection print when run?
Run it as a complete program — the output lines carry labels such as `exit code:`.