English | 简体中文
Integrate the locally installed Codex CLI with Spring Boot through auto-configuration, with support for synchronous and asynchronous execution, streaming events, cancellation, thread resumption, and structured output.
- Java 17+
- Spring Boot 3.x
- The
codexCLI is installed locally and authenticated (runcodex --versionto verify the installation)
<dependency>
<groupId>cn.junki</groupId>
<artifactId>codex-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>The starter automatically registers a CodexClient bean:
importcn.junki.codex.CodexClient;
importcn.junki.codex.CodexResponse;
importorg.springframework.stereotype.Service;
@ServicepublicclassCodingService {
privatefinalCodexClientcodexClient;
publicCodingService(CodexClientcodexClient) {
this.codexClient = codexClient;
}
publicStringrunTask(Stringtask) {
CodexResponseresponse = codexClient.execute(task);
returnresponse.output();
}
}execute is synchronous. It sends the task to codex exec --json through stdin, waits for the process to finish, and returns the final agent response. CodexResponse also contains the thread ID, token usage, elapsed time, and raw JSONL events.
Use submit when a task should not block the calling thread. The returned task
exposes a CompletableFuture and can terminate the CLI process and its child
processes when cancelled:
CodexTasktask = codexClient.submit("Run the tests and fix any failures");
task.future().thenAccept(response -> System.out.println(response.output()));
// When the result is no longer needed:task.cancel();Both synchronous and asynchronous executions can report typed JSONL events as soon as the CLI emits them:
CodexResponseresponse = codexClient.execute(
CodexRequest.builder("Refactor the service").build(),
event -> {
if (eventinstanceofCodexEvent.ItemCompletedcompleted) {
System.out.println(completed.item());
}
});Known event types are represented by ThreadStarted, ItemStarted,
ItemCompleted, and TurnCompleted. New or unrecognized CLI event types are
preserved as CodexEvent.Other, including their original JSON.
Persisted Codex threads can be continued using the thread ID returned by an earlier response:
CodexResponsefirst = codexClient.execute("Inspect the failing tests");
CodexResponsenext = codexClient.resume(
first.threadId(),
"Now implement the fixes you proposed");The same behavior is available through
CodexRequest.builder(prompt).threadId(threadId) when request-level options are
needed.
Provide a JSON Schema accepted by codex exec --output-schema, then ask the
client to deserialize the final response:
recordAnalysis(Stringsummary, List<String> findings) {}
CodexRequestrequest = CodexRequest.builder("Analyze this project")
.outputSchema(Path.of("analysis.schema.json"))
.build();
CodexStructuredResponse<Analysis> result =
codexClient.execute(request, Analysis.class);
Analysisanalysis = result.value();
CodexResponserawResponse = result.response();codex:
cli:
enabled: trueexecutable: codexworking-directory: /path/to/projecttimeout: 10mmodel: gpt-5.2-codex # Optional; uses the CLI configuration by defaultprofile: work # Optionalsandbox: workspace-write # read-only / workspace-write / danger-full-accessephemeral: falseskip-git-repo-check: falseadditional-arguments: []environment: {}Common options can also be overridden for an individual task:
CodexResponseresponse = codexClient.execute(CodexRequest.builder("Fix the tests and explain the cause")
.workingDirectory(Path.of("/path/to/project"))
.timeout(Duration.ofMinutes(20))
.sandbox(CodexSandbox.WORKSPACE_WRITE)
.ephemeral(true)
.build());A CodexCliException is thrown if the CLI cannot be started, returns a non-zero exit code, times out, or produces malformed output. For non-zero exits, use getExitCode() and getStandardError() to inspect the failure.
JAVA_HOME=$(/usr/libexec/java_home -v 21) mvn clean verifyThe test suite uses a temporary fake CLI, so it does not submit real Codex tasks or consume API quota.
To run the real CLI integration test, the local Codex CLI must be authenticated and have network access:
JAVA_HOME=$(/usr/libexec/java_home -v 21) \
mvn -Dcodex.integration-test=true \
-Dtest=CodexCliIntegrationTest testThis test submits How's the weather in Beijing today? to the local Codex CLI and verifies that both the final response and thread ID are non-empty. It is not included in the default mvn test run.
The project selects .mvn/settings.xml through .mvn/maven.config. Maven commands run in this project therefore do not read or modify ~/.m2/settings.xml in the user's home directory.
Central Portal credentials are provided through environment variables, so no plaintext tokens are stored in the configuration:
export CENTRAL_USERNAME='Central Portal token username'export CENTRAL_PASSWORD='Central Portal token password'
mvn -Prelease clean deployThe credentials can also be scoped to a single command:
CENTRAL_USERNAME='username' CENTRAL_PASSWORD='password' \
mvn -Prelease clean deployThe release profile builds the main, source, and Javadoc JARs, signs them with the local GPG key, and uploads the bundle to https://central.sonatype.com. After Portal validation succeeds, the current configuration waits for manual publication instead of releasing automatically:
# Validate release artifacts without signing or uploading
mvn -Prelease -Dgpg.skip=true clean verify
# Upload the release bundle
CENTRAL_USERNAME='username' CENTRAL_PASSWORD='password' \
mvn -Prelease clean deployAfter the upload completes, review the validation result on the Central Portal Deployments page and click Publish manually.
