Search code examples
javagradleintellij-ideaaspectjfreefair-aspectj

AspectJ in Gradle - Intellij Idea


For a whole day i've been trying to use AspectJ - adding dependencies, installing plugins, creating .aj files or marking with @Aspect annotation, but nothing seems to work on gradle. Please help me to understand my problem.

My GreetingAspect.aj file

package org.example;

public aspect GreetingAspect {

    pointcut greeting() : execution(* Main.printName(..));

    before() : greeting() {
        System.out.print("Hello ");
    }
}

The code should print "Hello (name)" before every instance of .printName(), so i can see that "poincut" and "before" is working

  1. My build.gradle
plugins {
    id 'java'
    id "io.freefair.aspectj" version "8.3"
}

group = 'org.example'
version = '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {

    testImplementation platform('org.junit:junit-bom:5.9.1')
    testImplementation 'org.junit.jupiter:junit-jupiter'

    runtimeOnly 'org.aspectj:aspectjweaver:1.9.7'
    runtimeOnly 'org.aspectj:aspectjrt:1.9.7'
    implementation 'org.aspectj:aspectjtools:1.9.7'

}

test {
    useJUnitPlatform()
}
  1. Main
package org.example;

public class Main {

    public static void main(String[] args) {
        printName("Max");
        printName("John");
        printName("Martin");
    }

    public static void printName(String name) {
        System.out.println(name);
    }
}

I tried to: Install AspectJ plugin from market, that added support for .aj, but they seem to do nothing at all, install AspectJ plugins from https://plugins.gradle.org/, Installing .jar directly in lib, Changing version from 1.9.10 to 1.9.7, instead of .aj using .java classes but with @Aspect annotation.


Solution

  • Maybe you have both source files in src/main/java or only the aspect in src/main/aspectj, but in the default configuration, Freefair expects all source files to reside in src/main/aspectj:

    Gradle project directory layout for Freefair AspectJ

    Then, the project works flawlessly.


    [Optional] You can, however, also streamline your Gradle build config a little bit and also update AspectJ to a more recent version, because 1.9.7 only supports Java 16, but 1.9.20 supports up to Java 20.

    plugins {
      id 'java'
      id "io.freefair.aspectj" version "8.3"
    }
    
    group = 'org.example'
    version = '1.0-SNAPSHOT'
    
    repositories {
      mavenLocal()
      mavenCentral()
    }
    
    dependencies {
      testImplementation platform('org.junit:junit-bom:5.9.1')
      testImplementation 'org.junit.jupiter:junit-jupiter'
      implementation 'org.aspectj:aspectjrt:1.9.20'
    }
    
    test {
      useJUnitPlatform()
    }
    

    Update 2023-10-10: Freefair 8.4 now defaults to src/main/java, i.e. it works as expected with a standard directory layout, just like with AspectJ Maven.