Declarative preconditions and postconditions for Java 25 applications.
contract-java lets application code declare semantic contracts with
annotations and enforces them at runtime through checks generated by a javac
annotation processor. Contract violations are programming errors: parameter
precondition failures throw IllegalArgumentException, and return-value
postcondition failures throw IllegalStateException.
contract-java is not an input-validation library. Read
contract-java vs. Jakarta Validation
before deciding where to use it.
Jakarta Validation (formerly Bean Validation; implemented by, for example,
Hibernate Validator) and contract-java both put constraint-like annotations
such as "positive", "size", or "pattern" on Java code. They look similar, but they solve different
problems. Use them together, not as alternatives:
- Jakarta Validation answers "Is this data acceptable?" It checks untrusted input that enters your system from outside.
contract-javaanswers "Is this code correct?" It checks the assumptions your own methods and constructors make about each other.
| Aspect | Jakarta Validation | contract-java |
|---|---|---|
| Question | Is this data acceptable? | Is this code correct? |
| Purpose | Reject invalid external input. | Detect programming errors. |
| A violation means | Bad input: expected, recoverable, and reported back to the client. | A bug: in the caller for a precondition, in the method itself for a postcondition. Unexpected and not recoverable. |
| Where it belongs | System boundaries such as controllers, message listeners, and forms. | Internal method and constructor boundaries. |
| How it runs | A validator, called by a framework or explicitly, that typically collects all violations. | Checks the annotation processor generates into the method body at compile time. They run on every call without proxies or a container, and fail fast on the first violation. |
| Failure signal | Constraint violations, for example ConstraintViolationException. |
IllegalArgumentException for preconditions, IllegalStateException for postconditions. |
| Typical HTTP result | 400-style client error. |
500; the starter's opt-in resolver never maps contract violations to 4xx. |
| Closest analogy | Form and input validation. | Guava Preconditions.checkArgument / checkState, assertions. |
Contract annotations are the declarative counterpart to imperative checks such
as Guava Preconditions: instead of repeating checks at the top of each method
body, you declare them once on the signature and the processor generates them.
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;
import media.barney.contract.Contract;
record CreateUserRequest(
@NotBlank @Size(max = 32) String tenant,
@Positive int limit) {
}
@RestController
class UserController {
private final UserService users;
UserController(UserService users) {
this.users = users;
}
@PostMapping("/users")
String create(@Valid @RequestBody CreateUserRequest request) {
return users.createUser(request.tenant(), request.limit());
}
}
@Service
class UserService {
@Contract.Pattern(regexp = "USR-[0-9]+")
String createUser(
@Contract.NotBlank @Contract.Size(max = 32) String tenant,
@Contract.Positive int limit) {
// ...
}
}@Valid rejects a malformed request before any business code runs, and the
client receives a 400. The contracts on UserService do not repeat that job.
They document and enforce what the service needs from any caller: this
controller, a scheduled job, another service, or code written after the next
refactoring. If a precondition fails, some caller skipped validation or computed
a wrong value. If the postcondition fails, createUser itself is broken. Both
are bugs to fix, not input to report back to a client.
The two @NotBlank annotations differ on null: Jakarta @NotBlank rejects
null, while @Contract.NotBlank, like every built-in contract, lets it pass.
If createUser must never receive a null tenant, declare that with JSpecify
and enforce it with NullAway.
- Validate all untrusted input at the system boundary with Jakarta Validation or another validation layer. Never rely on contracts to reject user input.
- Use contracts on internal APIs to state what callers must pass and what methods guarantee to return.
- Do not catch contract exceptions to recover. Fix the caller when a precondition fails and the method when a postcondition fails.
- Built-in contracts ignore
null. For nullness inside your code, use JSpecify and NullAway (see Annotation Examples).
| Artifact | JPMS module | Purpose |
|---|---|---|
media.barney:contract-core |
media.barney.contract.core |
Framework-agnostic annotations, runtime checks, masking, and annotation processor. |
media.barney:contract-spring-boot-starter |
media.barney.contract.spring.boot.starter |
Spring Boot auto-configuration plus optional web and actuator integrations on top of contract-core. |
contract-examples |
n/a | Test-scoped examples that build in CI but are skipped for Maven deploy. |
The supported library API lives in media.barney.contract plus the generated-code
runtime bridge in media.barney.contract.runtime. The Spring Boot starter's
supported Boot-facing API lives in media.barney.contract.spring.
The hosted Javadoc for the latest published release is available at
fabian-barney.github.io/contract-java/api/latest/.
Versioned Javadoc is published under /api/<version>/.
Anything in a package named internal is unsupported implementation detail and
may change without notice.
JPMS descriptors export only the supported packages. Internal implementation packages remain present in the artifacts for generated checks and optional integrations, but they are not exported as public modules.
contract-java follows semantic versioning; RELEASING.md
defines the version-bump rules. Starting with 1.0.0, both contract-core and
contract-spring-boot-starter have maintained public APIs. Breaking changes to
those APIs or documented behavior require a major version.
The compatibility promise covers APIs annotated with API Guardian
@API(status = MAINTAINED) and the documented generated-code contract.
The starter's auto-configuration class, configuration-properties class, and
nested settings types are maintained. Their documented property names, defaults,
conditional integrations, and exception mapping are part of the stable promise.
Packages named internal are outside the compatibility promise.
Breaking changes include:
- Removing or renaming supported annotations, annotation attributes, runtime bridge types, or supported JPMS exports.
- Changing supported annotation targets, retention, or repeatability in an incompatible way.
- Changing the generated-code call shape that compiled/generated contract code depends on.
- Changing documented exception types, including parameter and
constructor-parameter failures no longer throwing
IllegalArgumentExceptionor return-value failures no longer throwingIllegalStateException. - Changing documented null handling, masking guarantees, starter property defaults, or optional integration behavior incompatibly.
Previously generated code remains compatible with the maintained runtime bridge within each major release line. Supported Java and Spring Boot versions follow the support policy.
The compatibility promise does not cover implementation details such as
processor internals, packages named internal, exact bytecode instruction
order, synthetic local names, javac-private helper classes, or message wording
outside the documented generated-code contract.
Use contract-core directly in plain Java projects:
<dependency>
<groupId>media.barney</groupId>
<artifactId>contract-core</artifactId>
<version>3.0.0</version>
</dependency>Use the Spring Boot starter in Boot applications:
<dependency>
<groupId>media.barney</groupId>
<artifactId>contract-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>Gradle builds need Gradle 9.1 or newer.
Gradle Kotlin DSL:
import org.gradle.api.tasks.compile.JavaCompile
dependencies {
implementation("media.barney:contract-core:3.0.0")
annotationProcessor("media.barney:contract-core:3.0.0")
}
val contractProcessorJvmArgs = listOf(
"--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
"--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",
"--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED",
"--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED",
"--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED",
"--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED",
"--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED",
"--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED",
"--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
"--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
"--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED",
)
tasks.withType<JavaCompile>().configureEach {
options.compilerArgs.addAll(listOf("-parameters", "-Acontracts.enabled=true"))
options.isFork = true
options.forkOptions.jvmArgs =
(options.forkOptions.jvmArgs ?: emptyList()) + contractProcessorJvmArgs
}Gradle Groovy DSL:
dependencies {
implementation 'media.barney:contract-core:3.0.0'
annotationProcessor 'media.barney:contract-core:3.0.0'
}
def contractProcessorJvmArgs = [
'--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED',
'--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED',
'--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED',
'--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED',
'--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED',
'--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED',
'--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED',
'--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED',
'--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED',
'--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED',
'--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED',
]
tasks.withType(JavaCompile).configureEach {
options.compilerArgs += ['-parameters', '-Acontracts.enabled=true']
options.fork = true
options.forkOptions.jvmArgs =
(options.forkOptions.jvmArgs ?: []) + contractProcessorJvmArgs
}Spring Boot applications can use
media.barney:contract-spring-boot-starter:3.0.0 as the
implementation dependency while keeping media.barney:contract-core on the
annotationProcessor path.
The starter keeps enforcement in contract-core, but it now adds Boot-specific
auto-configuration for optional integrations:
contract.spring.web-exception-handler.enabled=falseby defaultcontract.spring.actuator-info.enabled=trueby default when actuator is on the classpath
javac runs the processor only when annotation processing is configured
explicitly; a processor that is only on the compile classpath is not run.
Enable processing and list contract-core on the annotation processor path.
Generated contract messages use the source-level parameter names exposed by
javac while it compiles the AST. The <parameters>true</parameters> setting is
still useful for application code that inspects method metadata through
reflection, but it is not required for generated contract messages. Pass
processor options through the Maven compiler plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>25</release>
<parameters>true</parameters>
<proc>full</proc>
<annotationProcessorPaths>
<path>
<groupId>media.barney</groupId>
<artifactId>contract-core</artifactId>
<version>3.0.0</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<arg>-Acontracts.enabled=true</arg>
</compilerArgs>
</configuration>
</plugin>The current processor rewrites javac trees and therefore needs access to
jdk.compiler internals while it runs. For Maven Wrapper builds, add these
exports to .mvn/jvm.config. The targets cover processor-path usage
(ALL-UNNAMED) and JPMS processor-module-path usage
(media.barney.contract.core):
--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED,media.barney.contract.core
--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED,media.barney.contract.core
--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED,media.barney.contract.core
--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED,media.barney.contract.core
--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED,media.barney.contract.core
--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED,media.barney.contract.core
Disable generation for a build with:
<arg>-Acontracts.enabled=false</arg>contract-core enforces contracts by generating calls into
media.barney.contract.runtime during javac annotation processing. The runtime
bridge package is part of the supported generated-code surface; packages named
internal are not.
The generated-code behavior promised within a compatible release line is:
- Parameter and constructor-parameter contract failures throw
IllegalArgumentException. - Return-value contract failures throw
IllegalStateException. - Parameter checks are inserted at executable entry before the original method
body; constructor checks follow any explicit
this(...)orsuper(...)invocation required by Java. - Return checks are applied before every non-void return path.
- Generated parameter checks carry source-line metadata for the annotated parameter when javac exposes it, otherwise the executable declaration line is used as the fallback.
- Generated return checks carry source-line metadata for the original return statement.
- Masking must continue to prevent raw masked values from appearing in generated violation messages.
The semver promise does not cover exact bytecode instruction order, synthetic local names, javac-internal helper classes, or exact wording of generated messages beyond the documented exception type, method/parameter context, contract identity, value-rendering, and masking behavior.
Lombok integration depends on Lombok copying contract annotations to generated
constructors, setters, builders, or other generated members. Contract checks are
injected into generated members that are visible when the contract processor
runs. If Lombok has already emitted null checks in that body, contract checks
are prepended before those statements; javac processor ordering itself is not a
contract-java semver guarantee. Built-in contracts remain null-safe, so Lombok
@NonNull checks remain responsible for null failures regardless of ordering.
The contract-examples module contains executable examples for built-in
contracts, custom composed annotations, and @Contract.Mask. It is included in
the reactor build so examples stay current without being published as a library
artifact.
Run the examples with:
./mvnw -pl contract-examples -am testimport media.barney.contract.Contract;
class UserService {
@Contract.Pattern(regexp = "USR-[0-9]+")
String findUser(
@Contract.Positive Integer limit,
@Contract.Size(min = 1, max = 32) String tenant) {
return "USR-42";
}
}Contracts are null-safe for object values. null is not a violation; use
dedicated nullness tooling such as JSpecify and NullAway when nullness matters.
Built-in contracts include:
@Contract.NotEmpty@Contract.NotBlank@Contract.Positive@Contract.Negative@Contract.NonNegative@Contract.NonPositive@Contract.InRange@Contract.Size@Contract.Pattern
Custom composed annotations are supported:
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import media.barney.contract.Contract;
@Contract
@Contract.Positive
@Target({PARAMETER, METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface ValidId {
String message() default "must be a valid ID";
}Use @Contract.Mask when a violating value must not appear in generated
exception messages:
void login(@Contract.Mask @Contract.Pattern(regexp = "[0-9]+") String token) {
// ...
}The default mask renderer emits [MASKED] and intentionally avoids revealing
length, substrings, or type-specific details. Custom renderers can be supplied
through @Contract.Mask(renderer = MyRenderer.class), but they should remain
non-sensitive by design.
Field contracts are supported as metadata so Lombok can copy them to generated
constructors, setters, getters, and builders. Add the annotations you use to
lombok.config:
lombok.copyableAnnotations += media.barney.contract.Contract.NotBlank
lombok.copyableAnnotations += media.barney.contract.Contract.NotEmpty
lombok.copyableAnnotations += media.barney.contract.Contract.Positive
lombok.copyableAnnotations += media.barney.contract.Contract.Size
lombok.copyableAnnotations += media.barney.contract.Contract.PatternField declarations are metadata and are not enforced directly. Contracts copied by Lombok onto supported method, constructor, or parameter targets are enforced.
contract-spring-boot-starter supports Spring Boot 4.0.x, 4.1.x, and
4.2.x.
The compatibility table follows the support policy. CI compiles and runs behavior tests against each listed Spring Boot line on every supported JDK, in addition to isolated dependency-resolution checks.
| JDK | Spring Boot 4.0.x |
Spring Boot 4.1.x |
Spring Boot 4.2.x |
|---|---|---|---|
| 25 | Tested and supported | Tested and supported | Tested and supported |
| Other Java releases | Unverified | Unverified | Unverified |
Building and running the annotation processor requires a full JDK 25. Published library bytecode targets Java 25. Use current security patches within the supported JDK lines; newer feature releases are unverified.
Spring Boot lines outside the support policy are not part of the starter support
target, even if contract-core remains usable in non-Spring projects.
The starter publishes Boot auto-configuration from
media.barney.contract.spring.ContractSpringAutoConfiguration and keeps the
contract processor in contract-core.
If contract.spring.web-exception-handler.enabled=true, the starter registers
an opt-in servlet HandlerExceptionResolver that only handles
contract-generated exceptions. Contract violations are programming errors, not
recoverable request-validation failures, so generated precondition and
postcondition violations both map to bodyless HTTP 500 responses. Use
Jakarta Validation or another request-validation layer for expected 4xx
input errors; see
contract-java vs. Jakarta Validation.
If actuator is on the classpath, contract.spring.actuator-info.enabled=true
adds a small InfoContributor entry showing that the starter is active.
Use the starter with a supported Spring Boot BOM or parent so the consuming application controls the exact Boot line.
The annotation processor rewrites javac trees, so the JVM running Maven must
export the javac internals used by the processor. If compilation fails with
IllegalAccessError, IllegalAccessException, or a message such as
module jdk.compiler does not export com.sun.tools.javac.*, add the exports to
.mvn/jvm.config so every Maven Wrapper command receives them.
Use this repository's .mvn/jvm.config entries as the Maven Wrapper baseline:
--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED
--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED
When running the processor on the JPMS processor module path, also export the
javac packages to media.barney.contract.core as shown in
Maven Compiler Setup.
| Symptom | Likely cause | Fix |
|---|---|---|
Contract messages use names such as arg0 or arg1 instead of source parameter names. |
The compiler did not expose a usable source parameter name to the processor. | Rebuild from normal Java source with annotation processing enabled. The processor reads names from javac's source AST; -parameters is for reflection metadata and does not control generated contract messages. |
| Annotated methods compile, but no generated checks run. | Contract processing is disabled or the build does not pass -Acontracts.enabled=true after overriding compiler arguments. |
Add <arg>-Acontracts.enabled=true</arg> to compiler arguments or remove any -Acontracts.enabled=false override. |
| Annotated methods compile, but the processor never appears to run. | contract-core is only on the compile classpath, or missing from the annotation processor path or processor module path. javac does not run processors that are only on the compile classpath. |
Add media.barney:contract-core as a dependency and to the annotation processor path: Maven annotationProcessorPaths with <proc>full</proc>, or the Gradle annotationProcessor configuration. |
| Lombok-generated constructors, setters, builders, or getters do not receive expected contract checks. | Lombok did not copy the contract annotations or processor ordering hides the generated member from the contract processor. | Add the relevant media.barney.contract.Contract.* annotations to lombok.copyableAnnotations and keep Lombok available before the contract processor sees generated members. Do not rely on exact Lombok null-check ordering as a compatibility guarantee. |
See CONTRIBUTING.md for local build, quality gate, and release-skeleton
commands.