Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspectJ + Gradle configuration

I'd like to use AspectJ in Gradle project (it's not an Android project - just a simple Java app).

Here is how my build.gradle looks like:

apply plugin: 'java'

buildscript {
    repositories {
        maven {
            url "https://maven.eveoh.nl/content/repositories/releases"
        }
    }
    dependencies {
        classpath "nl.eveoh:gradle-aspectj:1.6"
    }
}

repositories {
    mavenCentral()
}

project.ext {
    aspectjVersion = "1.8.2"
}

apply plugin: 'aspectj' 

dependencies {
    //aspectj dependencies
    aspectpath "org.aspectj:aspectjtools:${aspectjVersion}"
    compile "org.aspectj:aspectjrt:${aspectjVersion}"
}

The code compiles, however the aspect seems to not be weaved. What could be wrong?

like image 768
Kao Avatar asked Oct 05 '15 13:10

Kao


2 Answers

A bit ugly, but short and does not require additional plugins or configurations. Works for me:

Add aspectjweaver dependency ti Gradle build script. Then in the task you need it find the path to its jar and pass as javaagent in jvmArgs:

dependencies {
    compile "org.aspectj:aspectjweaver:1.9.2"
}

test {
    group 'verification'

    doFirst {
        def weaver = configurations.compile.find { it.name.contains("aspectjweaver") }
        jvmArgs = jvmArgs << "-javaagent:$weaver"
    }
}

Add aop.xmlfile to the resources\META-INF\ folder with the specified Aspect class:

<aspectj>
    <aspects>
        <aspect name="utils.listener.StepListener"/>
    </aspects>
</aspectj>

Example of an aspect:

package utils.listener

import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.*
import org.aspectj.lang.reflect.MethodSignature

@Aspect
@SuppressWarnings("unused")
public class StepListener {

    /* === Pointcut bodies. Should be empty === */
    @Pointcut("execution(* *(..))")
    public void anyMethod() {
    }

    @Pointcut("@annotation(org.testng.annotations.BeforeSuite)")
    public void withBeforeSuiteAnnotation() {
    }
}
like image 185
BohdanN Avatar answered Sep 20 '22 13:09

BohdanN


This plugin worked for me (gradle 5.6):

plugins {
    id 'java'
    id "io.freefair.aspectj.post-compile-weaving" version "4.1.4"
}
like image 20
OHY Avatar answered Sep 17 '22 13:09

OHY