Historical Note: This was originally written in early 2022.

I recently needed to develop an annotation processor in Kotlin to scaffold REST services code from entities.

The idea was straightforward: annotate an entity with a little configuration, then generate the corresponding repository, service, REST resource and supporting SQL artefacts.

The processor was written in Kotlin, using KAPT (Kotlin Annotation Processing Tool) and Java's annotation-processing API.

Here are the main pieces of the implementation.


Defining the Annotation

First, I created a class-level annotation to describe the entity and control which artefacts should be generated.

@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.CLASS)
annotation class CRUDEntity(
    val restPath: String,
    val overrideRepository: Boolean = false,
    val overrideService: Boolean = false,
    val overrideResource: Boolean = false,
    val generateAPIs: Boolean = true,
    val useSoftDelete: Boolean = false,
)

The SOURCE retention policy is appropriate here because the annotation is used during compilation rather than at runtime.

The properties allow each annotated entity to supply its REST path and customise aspects of the generated code.

This keeps the configuration close to the entity itself, rather than maintaining it separately.


Creating the Annotation Processor

The processor extends Java's AbstractProcessor class and is registered using Google's AutoService library.

@AutoService(Processor::class)
@SupportedOptions(CRUDEntityProcessor.KAPT_KOTLIN_GENERATED_OPTION_NAME)
class CRUDEntityProcessor : AbstractProcessor() {

    companion object {
        const val KAPT_KOTLIN_GENERATED_OPTION_NAME =
            "kapt.kotlin.generated"
    }

    override fun getSupportedAnnotationTypes(): MutableSet<String> {
        return mutableSetOf(CRUDEntity::class.java.canonicalName)
    }

    override fun getSupportedSourceVersion(): SourceVersion {
        return SourceVersion.latestSupported()
    }

    // Processing logic...
}

The @AutoService annotation registers the processor through Java's service-provider mechanism, allowing the annotation-processing infrastructure to discover it.

The getSupportedAnnotationTypes() method identifies the annotation this processor handles.

Although the implementation is written in Kotlin, it works with the familiar Java annotation-processing types, including RoundEnvironment, TypeElement and Filer.


Finding Annotated Entities

The main work happens in the processor's process() method.

Annotation processing can take place over multiple rounds. During each round, the processor examines the elements annotated with @CRUDEntity.

The essential lookup is:

roundEnv.getElementsAnnotatedWith(CRUDEntity::class.java)
    .forEach { element ->

        val classElement = element as TypeElement
        val qualifiedClassName =
            classElement.qualifiedName.toString()

        val crudEntity =
            element.getAnnotation(CRUDEntity::class.java)

        // Extract configuration and queue the entity
    }

For each annotated class, the processor extracts its qualified name and annotation properties.

These values are collected into an EntityConfig object, which is passed to the code generators.

The implementation also maintains collections of entities waiting to be processed and those already handled. This prevents the same entity from being generated repeatedly across processing rounds.


Generating the Artefacts

Once the entity configuration has been collected, the processor delegates the work to individual generators.

processList.forEach { (entityConfig, element) ->

    RepositoryGenerator.generate(
        processingEnv.filer, entityConfig
    )

    ResourceGenerator.generate(
        processingEnv.filer, entityConfig, element
    )

    ServiceGenerator.generate(
        processingEnv.filer, entityConfig, element
    )

    // Other generators...
}

Separating the generators keeps the processor relatively simple.

The processor is responsible for discovering annotations and coordinating the work, while each generator handles a particular type of output. The generators use templates to construct their source code and Java's Filer API to write the resulting files.

For example:

val builderFile = filer.createSourceFile(
    "${entityConfig.qualifiedName}Repository"
)

PrintWriter(builderFile.openWriter()).use { out ->
    out.println(code)
}

The generated source becomes part of the compilation process.

This approach also makes it straightforward to extend the system with additional generators.


Processing Field-Level Annotations

The implementation also supports annotations on individual entity properties.

For example, I introduced @ResourceFieldAccessor:

@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.FIELD)
annotation class ResourceFieldAccessor(
    val name: String = ""
)

This allows a property to request an additional REST resource method.

For example:

@ResourceFieldAccessor
var teamId: Int = 0

@ResourceFieldAccessor(name = "pos")
var position: String = ""

In the original CRUD example, these annotations were used to generate resource methods with paths such as:

/test/v1/player/teamId/{value}
/test/v1/players/pos/{value}

The generated methods retrieve entities matching the supplied property value.

The optional name property allows the URL path segment to differ from the Kotlin property name.

A helper examines the annotated fields and extracts the information needed by the resource, service and SQL generators.

The same annotation metadata can therefore be used to generate several related artefacts, including resource methods, service methods and database indexes.


How the Pieces Fit Together

The overall processing pipeline is relatively simple:

Annotated Kotlin entity
          |
          v
    KAPT / Processor
          |
          v
Discover annotations
and extract EntityConfig
          |
          v
   Individual generators
          |
          +----> Repository source
          |
          +----> Service source
          |
          +----> REST resource source
          |
          +----> SQL artefacts

The annotation processor coordinates the process, while the generators handle the implementation details.

This separation proved useful because new generation requirements could be accommodated without turning the processor into one large class.


A Few Considerations

This implementation uses KAPT and Java's annotation-processing API rather than Kotlin Symbol Processing (KSP).

It was a practical way to implement compile-time code generation in Kotlin while working with the established Java annotation-processing infrastructure.

Annotation processing introduces its own complexity, but for predictable scaffolding, it provided a practical way to reduce repetitive work without introducing a more elaborate code-generation pipeline.


Final Thoughts

By combining source-retained annotations, Java's annotation-processing API and a collection of focused generators, I was able to automate the creation of repositories, services, REST resources and supporting SQL artefacts.

The implementation also reinforced a useful design principle: keep the mechanism that discovers and coordinates work separate from the components that perform it.

For this particular project, that separation made the annotation processor easier to understand and extend.