13

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?

Kao
  • 7,225
  • 9
  • 41
  • 65
  • For gradle 5 u can use this ['official' plugin](https://plugins.gradle.org/plugin/io.freefair.aspectj.post-compile-weaving). there you can find a working example too. – Vitali Zarembouski Jan 28 '19 at 14:17

6 Answers6

10

I have been struggled with this for a while, so this the config I use and works well.

In your configuration do this.

configurations {
    ajc
    aspects
    aspectCompile
    compile{
        extendsFrom aspects
    }
}

In your dependencies use the following configuration. Spring dependencies are not needed if you are not using spring fwk.

dependencies {

    //Dependencies required for aspect compilation
    ajc "org.aspectj:aspectjtools:$aspectjVersion"
    aspects "org.springframework:spring-aspects:$springVersion"
    aspectCompile  "org.springframework:spring-tx:$springVersion"
    aspectCompile  "org.springframework:spring-orm:$springVersion"
    aspectCompile  "org.hibernate.javax.persistence:hibernate-jpa-2.1-api:$hibernateJpaVersion"

}

compileJava {
    sourceCompatibility="1.7"
    targetCompatibility="1.7"
    //The following two lines are useful if you have queryDSL if not ignore
    dependsOn generateQueryDSL
    source generateQueryDSL.destinationDir

    dependsOn configurations.ajc.getTaskDependencyFromProjectDependency(true, "compileJava")

    doLast{
        ant.taskdef( resource:"org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath)
        ant.iajc(source:"1.7", target:"1.7", destDir:sourceSets.main.output.classesDir.absolutePath, maxmem:"512m", fork:"true",
                aspectPath:configurations.aspects.asPath,
                sourceRootCopyFilter:"**/.svn/*,**/*.java",classpath:configurations.compile.asPath){
            sourceroots{
                sourceSets.main.java.srcDirs.each{
                    pathelement(location:it.absolutePath)
                }
            }
        }
    }
}

I dont use the plugin I use the ant and aspectj compiler to do that, probably there will be an easy way

Koitoer
  • 18,778
  • 7
  • 63
  • 86
7

Just want to add the so called "official" plugin for AspectJ mentioned by Archie.

Here's some gradle script example on how to do it:

apply plugin: 'java'



sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

if (!hasProperty('mainClass')) {
    ext.mainClass = 'com.aspectz.Main'
}
buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "gradle.plugin.aspectj:gradle-aspectj:0.1.6"
    //classpath "gradle.plugin.aspectj:plugin:0.1.1"
    //classpath "gradle.plugin.aspectj:gradle-aspectj:0.1.1"
  }
}


ext {
    aspectjVersion = '1.8.5'
}

apply plugin: "aspectj.gradle"


repositories {
    mavenCentral()
}

dependencies {

    testCompile group: 'junit', name: 'junit', version: '4.10'
    compile("log4j:log4j:1.2.16")
    compile("org.slf4j:slf4j-api:1.7.21")
    compile("org.slf4j:slf4j-log4j12:1.7.21")
    compile("org.aspectj:aspectjrt:1.8.5")
    compile("org.aspectj:aspectjweaver:1.8.5")


}

However, it seems that it only supports Java 8 and above. As when you use java 7 to build it, it got error :

java.lang.UnsupportedClassVersionError: aspectj/AspectJGradlePlugin : Unsupported major.minor version 52.0
MazBeye
  • 666
  • 7
  • 12
  • 3
    `if (!hasProperty('mainClass')) { ext.mainClass = 'com.aspectz.Main' }` is this a mandatory ? – Adams.H Mar 03 '19 at 06:18
4

Looks like there is a new "official" gradle plugin for AspectJ:

https://plugins.gradle.org/plugin/aspectj.gradle

Unfortunately the documentation is minimal. I haven't tried it myself.

Archie
  • 4,959
  • 1
  • 30
  • 36
  • 3
    the plugin is no longer maintained and also doesn't work anymore ("Could not get unknown property 'classesDir' [...]"): see https://github.com/eveoh/gradle-aspectj/commit/9cf44ebf5ecb8073db9eb9a5230e4c69558f0268 – PixelMaster Feb 18 '20 at 16:47
  • these days i try to aovid gradle. just my opinion. – Archie Feb 18 '20 at 20:05
  • yeah, I would too. Unfortunately, I have to use it at work :( – PixelMaster Feb 19 '20 at 17:43
4

This plugin worked for me (gradle 5.6):

plugins {
    id 'java'
    id "io.freefair.aspectj.post-compile-weaving" version "4.1.4"
}
OHY
  • 890
  • 1
  • 8
  • 14
3

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() {
    }
}
Bohdan Nesteruk
  • 794
  • 17
  • 42
1

Adding this in my build.gradle file worked for me.

project.ext {
  aspectjVersion = '1.8.12'
}

apply plugin: "aspectj.gradle"

buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "gradle.plugin.aspectj:gradle-aspectj:0.1.6"
  }
}

Doing a gradle assemble injected the code defined in the aspect.

Erwin Alberto
  • 1,064
  • 10
  • 7