AspectJ + Gradle configuration

Kao picture Kao · Oct 5, 2015 · Viewed 18.4k times · Source

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?

Answer

Koitoer picture Koitoer · Feb 6, 2016

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