Skip to content

AOP Overview

Aspect-Oriented Programming (AOP) separates cross-cutting concerns from business logic. A cross-cutting concern is code that many unrelated functions need, such as logging, authentication or metrics.

The Problem: Cross-Cutting Concerns

Without AOP, the same lines are repeated in every function:

fun processPayment(amount: Double, userId: String) {
    logger.info("processPayment called")     // logging
    checkAuthenticated(userId)               // auth
    metrics.increment("payment.calls")       // metrics
    // --- actual business logic ---
    chargeCard(amount, userId)
}

fun refundPayment(paymentId: String) {
    logger.info("refundPayment called")      // logging (again)
    checkAuthenticated(userId)               // auth (again)
    metrics.increment("refund.calls")        // metrics (again)
    // --- actual business logic ---
    reverseCharge(paymentId)
}

The AspectK Solution

With AspectK, each concern lives in one aspect and the functions only carry annotations:

// Business logic
@Logged @Authenticated @Metered
fun processPayment(amount: Double, userId: String) {
    chargeCard(amount, userId)
}

@Logged @Authenticated @Metered
fun refundPayment(paymentId: String) {
    reverseCharge(paymentId)
}

// The logging concern, in one place
@Aspect
object LoggingAspect {
    @Before(target = [Logged::class])
    fun log(jp: JoinPoint) = logger.info("${jp.signature.methodName} called")
}

Design Philosophy

Why not AspectJ?

AspectJ can express more than any other AOP framework on the JVM, and its pointcut expression language is where the cost shows up:

// AspectJ — string-based pointcut expression
@Aspect
public class LoggingAspect {
    @Before("execution(* com.example.service.*.*(..)) && " +
            "@annotation(com.example.Logged) && " +
            "within(com.example..*)")
    public void log(JoinPoint jp) { ... }
}

Problems with this approach:

  • Pointcuts are plain strings. A typo compiles fine and only shows up when the advice silently fails to apply.
  • Renaming a class or method doesn't update the pointcut string.
  • The expression language (execution(), within(), args() and so on) takes time to learn.
  • AspectJ works on JVM bytecode, so it cannot target Kotlin Multiplatform.

AspectK: Type-Safe Pointcuts

AspectK uses KClass references instead of strings, so the compiler checks every pointcut:

// AspectK — type-safe, no strings, no runtime container
@Aspect
object LoggingAspect {
    @Before(target = [Logged::class])  // KClass reference, not a string
    fun log(jp: JoinPoint) { ... }
}
AspectJ AspectK
Pointcut definition String expression KClass reference
Type-safe? ❌ No ✅ Yes
Refactor-safe? ❌ No ✅ Yes
Runtime dependency ❌ No (weave-time) ❌ No
KMP support ❌ JVM only ✅ All targets

The target parameter takes KClass<out Annotation> references. Rename an annotation class and the IDE updates every aspect that references it. Delete one and those aspects stop compiling.


How Injection Works: Before vs After Compilation

AspectK uses the K2 IR (Intermediate Representation) transformation API. After your source is parsed and type-checked, the compiler plugin walks the IR tree and inserts advice calls into the matching function bodies.

Before Compilation (your source code)

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.BINARY)
annotation class Logged

@Aspect
object LoggingAspect {
    @Before(target = [Logged::class])
    fun log(joinPoint: JoinPoint) {
        println("→ ${joinPoint.signature.methodName}(${joinPoint.args.joinToString()})")
    }
}

class OrderService {
    @Logged
    fun placeOrder(orderId: String, amount: Double) {
        println("Order placed: $orderId, $amount")
    }
}

After IR Transformation (equivalent generated code)

The plugin rewrites placeOrder so that the advice call is the first statement of the body:

// You don't write this. It shows what the compiler generates.
// AspectK generates the names containing `$`, which is why they are backtick-quoted here.

class OrderService {
    // Generated by AspectK: synthetic inner object holding compile-time metadata,
    // initialized once per class load (not per call).
    private object `$MethodSignatures` {
        val `ajc$tjp_0`: MethodSignature = MethodSignature(
            methodName = "placeOrder",
            annotations = listOf(
                AnnotationInfo(Logged::class, "com.example.Logged", emptyList(), emptyList()),
            ),
            parameter = listOf(
                // The dispatch receiver (this) is always the first entry
                MethodParameter("<this>", OrderService::class, "com.example.OrderService", emptyList(), false),
                MethodParameter("orderId", String::class, "kotlin.String", emptyList(), false),
                MethodParameter("amount",  Double::class, "kotlin.Double", emptyList(), false),
            ),
            returnType = Unit::class,
            returnTypeName = "kotlin.Unit",
        )
    }

    fun placeOrder(orderId: String, amount: Double) {
        // ↓ Injected by AspectK at compile time
        LoggingAspect.log(
            DefaultJoinPoint(
                target    = this,
                signature = `$MethodSignatures`.`ajc$tjp_0`,
                // args[0] is always the dispatch receiver (this) for member functions,
                // followed by the declared value parameters in order
                args      = listOf(this, orderId, amount),
            )
        )
        // ↓ Original function body, unchanged
        println("Order placed: $orderId, $amount")
    }
}

What to notice

  • The @Before advice call is the first statement of the transformed body. It is a direct function call, with no wrapper and no proxy object.
  • MethodSignature is initialized once per class load, not once per call. AspectK generates a synthetic object $MethodSignatures inside the containing class, with one property per intercepted function (ajc$tjp_0, ajc$tjp_1, …).
  • For member functions, JoinPoint.args starts with the dispatch receiver (this), followed by the value parameters in declaration order. Top-level functions have no dispatch receiver, so args holds only the value parameters and target is null.
  • MethodSignature.parameter has the same layout as JoinPoint.args. For member functions the first entry is the <this> receiver parameter.
  • @Before leaves the original body as it is and only prepends to it. @After wraps the body in try/finally, and @Around moves it into a lambda. See @After and @Around.
  • The generated code is ordinary Kotlin and needs no framework at runtime beyond the small aspectk-runtime library that defines JoinPoint and its related classes.

AspectK vs AspectJ: Full Comparison

Feature AspectK AspectJ
Language Kotlin Java / Kotlin
Injection Compile-time (K2 IR) Compile-time (bytecode) / Load-time
Pointcut style Annotation KClass reference String expression language
Type-safe pointcuts ✅ Yes ❌ No
Refactor-safe ✅ Yes (compiler errors) ❌ No (silent breakage)
KMP support ✅ Full (JVM, JS, WASM, Native) ❌ JVM only
Runtime overhead ❌ None ❌ None (compile-time weaving)
Reflection at runtime ❌ No ❌ No
Advice types @Before, @After, @Around @Before, @After, @AfterReturning, @AfterThrowing, @Around
Learning curve Low (plain Kotlin) High (expression language)

Terminology

Term Meaning in AspectK
Aspect An object annotated with @Aspect
Advice A method inside an aspect annotated with @Before, @After or @Around
Join Point A function into which advice is injected
Pointcut An annotation class listed in an advice's target = [...]
Injection The K2 IR transformation that inserts advice calls at compile time. AOP literature calls this weaving