Search code examples
kotlingradleaspectj

Using Freefair AspectJ plugin in a Kotlin project (using gradle)


I'm having trouble configuring AspectJ in my kotlin project. I'm using freefair plugin but it doens't seem to be working. I start my application with no issues but the aspects are not taken into consideration.

I placed my aspect within the src/main/aspectj source directory in a file MetricAspect.kt

What I have right now is a gradle.build.kts file that looks something like this:

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile


plugins {
    //other plugins

    id("io.freefair.aspectj") version "6.6.3"

    val kotlinVersion = "1.7.21"
    kotlin("jvm") version kotlinVersion
    kotlin("plugin.spring") version kotlinVersion

    //other plugins
}


allprojects {
    apply(plugin = "org.jetbrains.kotlin.jvm")
    apply(plugin = "io.gitlab.arturbosch.detekt")
    apply(plugin = "com.diffplug.spotless")
    apply(plugin = "io.freefair.aspectj")
    apply(plugin = "kotlin-spring")
    version = "1.0.0-SNAPSHOT"

    java {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }

    

    repositories {
        maven {
            url = uri("https://private.repo/public-maven-virtual/")
            credentials {
                username = user
                password = password
            }
        }
    }

    dependencies {

        kotlinCompilerPluginClasspath("gradle.plugin.aspectj:gradle-aspectj:0.1.6")
        
        //other deps

        implementation("org.aspectj:aspectjrt:1.9.7")
        annotationProcessor("org.aspectj:aspectjtools:1.9.7")

        //other deps
    }

    tasks.withType<KotlinCompile> {
        kotlinOptions {
            freeCompilerArgs = listOf("-Xjsr305=strict")
            jvmTarget = "17"
        }
    }

    tasks.withType<Test> {
        useJUnitPlatform()
    }

    spotless {
        //....
    }

    detekt {
        buildUponDefaultConfig = true // preconfigure defaults
        allRules = false // activate all available (even unstable) rules.
        parallel = true
        config = files("$rootDir/detekt.yml")
    }
}

tasks {
    bootJar {
        enabled = false
    }
}

The documentation on it is pretty scarce and everyone seems to have its one way to configure this plugin, which is weird. Is there any official way to do this?


Solution

  • The AspectJ compiler only understands annotation-based Java syntax and native AspectJ syntax. If you want to use other JVM languages like Kotlin, you need to use post-compile weaving. Freefair has an option for that.