Kest

Search

Search the documentation

Kest

Using Kest from Java

Set up a Java-only backend, and write modules, controllers, entities, guards, decorators, relations and tests in Java.

Kest is written in Kotlin, but a backend can be entirely Java. The repository's examples/java-api is such an application and is tested against a real PostgreSQL. This page walks through it.

Why Kotlin appears in the build

The Kest processor is a KSP plugin, and KSP runs through the Kotlin compiler's Gradle plugin, which also reads your .java files. You write no Kotlin; the build file just applies the plugin.

1. The build

build.gradle.kts
plugins {
    kotlin("jvm") version "2.3.21"                     // only to host KSP
    id("com.google.devtools.ksp") version "2.3.13"
    application
}
repositories { mavenCentral() }
java { toolchain { languageVersion.set(JavaLanguageVersion.of(21)) } }
kotlin { jvmToolchain(21) }
 
dependencies {
    implementation(platform("io.kest.framework:bom:0.4.0"))
    implementation("io.kest.framework:core")
    implementation("io.kest.framework:http-server")
    implementation("io.kest.framework:http-server-netty")
    implementation("io.kest.framework:json-jackson")
    implementation("io.kest.framework:validation")
    implementation("io.kest.framework:orm")
    implementation("io.kest.framework:orm-postgres")
    ksp(platform("io.kest.framework:bom:0.4.0"))        // the BOM must be applied to ksp too
    ksp("io.kest.framework:processor")
}
application { mainClass.set("shop.Application") }
gradle.properties
ksp.useKSP2=true

Keep sources in src/main/java. Name the parameter in the annotation (@Param("id"), @Query("author")): Java does not keep parameter names unless you compile with -parameters, so naming them is the reliable way.

2. Modules and providers

Annotation arrays use Java's braces. Dependencies are constructor parameters.

@Injectable
public class BookService {
    private final BookRepository books;
    public BookService(BookRepository books) { this.books = books; }   // the processor picks the constructor with the most parameters
}
 
@Module(
    imports = {OrmModule.class, JacksonJsonModule.class, ValidationModule.class},
    providers = {BookRepository.class, BookService.class, ApiKeyGuard.class},
    controllers = {BookController.class})
public class AppModule { }

The module graph is checked at build time just as in Kotlin: a missing provider fails the build with a message that says which module should export it.

3. Starting the application

public class Application {
    static DynamicModule orm() {
        return OrmModule.forRoot(b -> {
            b.setSynchronize(true);
            Postgres.postgres(b, "main", System.getenv("PG_URL"), "app", "secret", 10);
        });
    }
 
    public static void main(String[] args) throws InterruptedException {
        Container app = Kest.run(AppModule.class, o -> o.importModules(orm()));
        KestHttp.start(app, new NettyHttpAdapter(8080), http -> {
            http.useGuards(ApiKeyGuard.class);
            http.usePipes(ValidationPipe.class);
            Docs.use(http, d -> d.setTitle("Library API"));
        });
        Thread.currentThread().join();
    }
}

Kest.run and Kest.create take the module class and a Consumer<Overrides>. Every Kotlin function that takes a lambda with receiver has a Consumer or KestHttp form for Java. Overrides offers override(Type.class, instance), provide(Type.class, r -> ...), provideAsync(Type.class, r -> future) and importModules(...).

4. Controllers

@Controller("/books")
public class BookController {
    private final BookRepository books;
    public BookController(BookRepository books) { this.books = books; }
 
    @Get
    public List<Book> list(@Query("author") @Nullable String author) {
        return author == null ? books.findAll() : books.findByAuthorOrderByTitleAsc(author);
    }
 
    @Get("/{id}")
    public Book get(@Param("id") long id) {
        return books.findOptional(id).orElseThrow(() -> new NotFoundException("Book " + id + " not found"));
    }
 
    @Post
    public Book create(@Body CreateBookDto dto) { return books.save(new Book(null, dto.isbn(), dto.title(), dto.author(), dto.pages(), 0)); }
 
    @Role("LIBRARIAN") @HttpCode(204) @Delete("/{id}")
    public void remove(@Param("id") long id) { if (!books.deleteById(id)) throw new NotFoundException("Book " + id + " not found"); }
 
    @Get("/long")
    public List<Book> longBooks(@Query(value = "pages", defaultValue = "500") int pages) { return books.findByPagesGreaterThan(pages); }
}
  • Java has no T?, so a parameter is optional when annotated @Nullable (any package).
  • Optional<T> return types work for repositories and for handlers.
  • Request bodies can be records with validation annotations, which the processor reads from the source:
record CreateBookDto(
    @NotBlank String isbn,
    @NotBlank @Size(min = 2, max = 80) String title,
    @NotBlank String author,
    @Positive int pages) { }

The raw request and response, object binding and custom parameter decorators work the same way: @Request HttpRequest req, @Response RawResponse res, @Query SearchDto dto. The raw-object forms are written for Kotlin data classes; in Java prefer the named forms above.

5. Entities and repositories

A record is an immutable entity:

@Entity("books")
public record Book(
    @Id @Generated Long id,
    @Unique @Column(nullable = false) String isbn,
    @Column(nullable = false) String title,
    @Column(nullable = false) String author,
    int pages,
    @Version long version) { }

A mutable class with a no-argument constructor, getters and setters works too, and is the form for relations:

@Entity("clubs")
public class Club {
    @Id @Generated private String id;
    private String name;
    @OneToMany(target = Member.class, mappedBy = "clubId", cascade = {Cascade.PERSIST, Cascade.REMOVE}, orphanRemoval = true)
    private List<Member> members;                 // null means "not loaded"
    @OneToMany(target = Member.class, mappedBy = "clubId")
    private kotlin.Lazy<List<Member>> roster;     // loads on first access
    // no-arg constructor, getters and setters
}
 
@Repository("main")
public interface ClubRepository extends CrudRepository<Club, String> { }
 
@Repository("main")
public interface BookRepository extends CrudRepository<Book, Long> {
    Optional<Book> findByIsbn(String isbn);
    List<Book> findByAuthorOrderByTitleAsc(String author);
    long countByAuthor(String author);
    @NativeQuery("select * from books where title ilike :pattern order by id")
    List<Book> searchTitles(String pattern);
}

Derived queries, @Column options, @Index, junction tables, cascades, orphan removal and lazy loading all work on mutable classes; relations are not supported on records (a record cannot be copied with a loaded relation). Java repository methods use findOptional where Kotlin has findById.

Club saved = clubs.save(club);                              // cascade: members saved with their foreign key
Club loaded = clubs.findWith(saved.getId(), "members");     // relation names are strings
loaded.getRoster().getValue();                              // the lazy property

6. Guards, interceptors, filters and decorators

Java has no coroutines, so the pipeline interfaces have blocking base classes:

@Injectable
class ApiKeyGuard extends BlockingGuard {
    @Override public boolean check(ExecutionContext ctx) {
        if (ctx.annotation(Public.class) != null) return true;              // handler first, then the controller
        String key = ctx.getRequest().header("x-api-key");
        if (key == null) throw new UnauthorizedException("Missing X-Api-Key");
        ctx.setPrincipal(new SimplePrincipal(key, Set.of("LIBRARIAN")));
        return true;
    }
}

BlockingInterceptor (override intercept(ctx, BlockingCall next)) and BlockingExceptionFilter are the other two. Custom decorators are Java annotations:

@io.kest.http.Metadata @Retention(RetentionPolicy.RUNTIME) @Target({METHOD, TYPE})
@interface Public { }
 
@io.kest.http.Guarded(guard = QuotaGuard.class) @Retention(RetentionPolicy.RUNTIME) @Target({METHOD, TYPE})
@interface Quota { int perCaller() default 3; }

Composite annotations (@UseGuards(...) on your own annotation), @ParamDecorator and @MethodAspect are plain Java annotations too; an aspect wrapper is a class implementing AspectWrapper:

@MethodAspect(AuditAspect.class) @Retention(RetentionPolicy.RUNTIME) @Target(METHOD)
@interface Audited { String action(); }
 
public class AuditAspect implements AspectWrapper {
    @Override public Object around(Annotation annotation, MethodCall call) {
        Object result = call.proceed();
        log.record(((Audited) annotation).action(), call.getMethod());
        return result;
    }
}

The method's class must be non-final with non-final methods (Java's default), as for Kotlin's open.

7. Tests

@Test void createsAndReadsABook() throws Exception {
    Container app = Kest.create(AppModule.class, o -> o.importModules(Application.orm()));
    RunningServer server = KestHttp.start(app, new JdkHttpAdapter(0), http -> http.useGuards(ApiKeyGuard.class));
    try {
        HttpResponse<String> r = HttpClient.newHttpClient().send(HttpRequest.newBuilder(URI.create("http://localhost:" + server.getPort() + "/books"))
            .header("x-api-key", "secret").POST(HttpRequest.BodyPublishers.ofString("{\"isbn\":\"1\",\"title\":\"Ab\",\"author\":\"X\",\"pages\":10}")).header("content-type", "application/json").build(), HttpResponse.BodyHandlers.ofString());
        assertEquals(201, r.statusCode());
    } finally { server.stop(); app.close(); }
}

Testing.createModule(AppModule.class, o -> { ... }) gives a TestingModule whose get(Type.class) returns a provider, and o.override(Type.class, fake) replaces one.

8. Differences from Kotlin, in one place

KotlinJava
Optional parameterInt?@Nullable
Handlersmay be suspendblocking (virtual threads make that cheap)
Guards and interceptorsGuard, InterceptorBlockingGuard, BlockingInterceptor
Entitiesdata classesrecords (no relations) or mutable classes
Lazy relationLazy<List<T>>kotlin.Lazy<List<T>>
Configuration blockslambdas with receiverConsumers and KestHttp.start
open for decorated methodsrequirednon-final is the default

What is tested

examples/java-api runs against PostgreSQL: records and POJOs as entities, derived and native queries, Java guards, interceptors, filters, decorators, validation on records, API docs, and cascade, orphan removal and lazy loading on Java classes.

Not built

A Java-flavoured kest generator (it writes Kotlin), provideSuspend and @Transactional-style suspend support (irrelevant to Java), and Java overloads for every Kotlin helper: where one is missing you can call the Kotlin one directly, since both are ordinary JVM classes.