Building a Kotlin + Java 9 project with Gradle - java

I'm fairly new to Gradle (and Java 9, to be honest), and I'm trying to use Gradle to build a simple library project that is a mix of Java 9 and Kotlin. More in detail, there is an interface in Java and an implementation in Kotlin; I'd do everything in Kotlin, but the modules-info.java is java anyway, so I decided to do things this way.
I'm building on IntelliJ Idea, with the 1.2.0 kotlin plugin and gradle 4.3.1 defined externally.
Filesystem schema is:
+ src
+ main
+ java
+ some.package
- Roundabout.java [an interface]
- module-info.java
+ kotlin
+ some.package.impl
- RoundaboutImpl.kt [implementing the interface]
module-info.java is:
module some.package {
requires kotlin.stdlib;
exports some.package;
}
and build.gradle is:
buildscript {
ext.kotlin_version = '1.2.0'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
group 'some.package'
version '1.0-PRE_ALPHA'
apply plugin: 'java-library'
apply plugin: 'kotlin'
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
sourceCompatibility = 9
compileJava {
dependsOn(':compileKotlin')
doFirst {
options.compilerArgs = [
'--module-path', classpath.asPath,
]
classpath = files()
}
}
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: "$kotlin_version"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
Notice that I had to specify a module path on the java compile task, or the compilation fails with:
error: module not found: kotlin.stdlib
requires kotlin.stdlib;
Anyway, now this build fails with this error, and I can't figure out how to solve it:
error: package some.package.impl does not exist
import some.package.impl.RoundaboutImpl;
error: cannot find symbol
return new RoundaboutImpl<>(queueSize, parallelism, worker, threadPool);
I think that the Kotlin part of the compilation is going ok, then the java part fails because it doesn't "see" the kotlin side, so to speak.
I think I should tell it somehow to to load the already compiled kotlin classes in the classpath; but (first) how do I do this in gradle? and (second) is it even possible? I think you can't mix module path and class path in Java 9.
How can I solve this? I think it is a pretty common situation, as every java9-style module will be a mixed-language module (because of module-info.java), so I think I'm missing something really basic here.
Thanks in advance!

Solved! It was sufficient to set the kotlin compilation dir to the same dir as Java:
compileKotlin.destinationDir = compileJava.destinationDir
It works now, both with the sources in the same tree or in different trees; but with a quirk: the jar task produces a jar with all the entries duplicated. I'll work on fix this, next.
Thanks to everyone!

I am using the following gradle script where I put the module-info.java under src/module. It gets automatically included in the jar (without duplicates):
if (JavaVersion.current() >= JavaVersion.VERSION_1_9) {
subprojects {
def srcModule = "src/module"
def moduleInfo = file("${project.projectDir}/$srcModule/module-info.java")
if (moduleInfo.exists()) {
sourceSets {
module {
java {
srcDirs = [srcModule]
compileClasspath = main.compileClasspath
sourceCompatibility = '9'
targetCompatibility = '9'
}
}
main {
kotlin { srcDirs += [srcModule] }
}
}
compileModuleJava.configure {
dependsOn compileKotlin
destinationDir = compileKotlin.destinationDir
doFirst {
options.compilerArgs = ['--module-path', classpath.asPath,]
classpath = files()
}
}
jar.dependsOn compileModuleJava
}
}
}
I won't update it any longer, have a look at https://github.com/robstoll/atrium/blob/master/build.gradle
to see the current version in use.

The accepted answer did not work for me (atleast not the way it was presented), but this is what worked:
plugins {
id "org.jetbrains.kotlin.jvm" version "1.3.50"
}
compileKotlin {
doFirst {
destinationDir = compileJava.destinationDir
}
}
jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
Doing it the way the accepted answer suggests led to me getting this error:
Directory '/path/to/project/build/classes/kotlin/main' specified for
property 'compileKotlinOutputClasses' does not exist.
Gradle version: 5.6

I ran into the same problem and the existing answers fixed only part of the issue for me, so I searched over all internet and ended up with a working solution. I don't know exactly why this works, but I decided to share my build.gradle.kts file here to help other people to find they way. This file is a combination of many pieces that I found on the internet.
I'm using Java 16, Kotlin 1.5.31 and Gradle 7.1.
The file tree is:
+ project
- build.gradle.kts
+ src
+ main
+ java
- module-info.java
+ my
+ package
- SomeClasses.java
+ kotlin
+ my
+ package
- MoreClasses.kt
module-info.java
module name.of.your.javamodule {
requires kotlin.stdlib;
requires kotlinx.coroutines.core.jvm;
requires org.jetbrains.annotations;
exports my.pacakge;
}
build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
application
kotlin("jvm") version "1.5.31"
id("org.jetbrains.kotlin.plugin.serialization") version "1.5.31"
}
val kotlinVersion = "1.5.31"
group = "your.group.id"
version = "0.0.1-SNAPSHOT"
application {
mainClass.set("full.name.of.your.MainClass")
mainModule.set("name.of.your.javamodule") // Same defined in module-info.java
executableDir = "run"
}
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib-jdk8", kotlinVersion))
implementation("com.michael-bull.kotlin-inline-logger:kotlin-inline-logger:1.0.3")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2-native-mt")
implementation("org.jetbrains:annotations:22.0.0")
testImplementation(kotlin("test", kotlinVersion))
}
java {
sourceCompatibility = JavaVersion.VERSION_16
targetCompatibility = JavaVersion.VERSION_16
}
tasks {
run.configure {
dependsOn(jar)
doFirst {
jvmArgs = listOf(
"--module-path", classpath.asPath
)
classpath = files()
}
}
compileJava {
dependsOn(compileKotlin)
doFirst {
options.compilerArgs = listOf(
"--module-path", classpath.asPath
)
}
}
compileKotlin {
destinationDirectory.set(compileJava.get().destinationDirectory)
}
jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
jvmTarget = "16"
}
}

On gradle 7.4 with kotlin DSL, I need to:
move the module-info.java to src/main/java
create any java file inside each package to export under src/main/java, at least empty package-info.java
In build.gradle.kts:
val compileKotlin: KotlinCompile by tasks
val compileJava: JavaCompile by tasks
compileKotlin.destinationDirectory.set(compileJava.destinationDirectory)
Also discussed here:
https://github.com/gradle/gradle/issues/17271

Related

IntelliJ: Unresolved reference, but gradle build still succeeds

I have a Java library https://github.com/skycavemc/skycavelib which I want to use in a Kotlin project. This is the build.gradle where I have the library as dependency:
import java.util.Properties
import java.io.FileInputStream
plugins {
kotlin("jvm") version "1.7.10"
}
group = "de.skycave"
version = "1.0.0"
val localProperties = Properties()
localProperties.load(FileInputStream(rootProject.file("local.properties")))
repositories {
mavenCentral()
maven { url = uri("https://repo.papermc.io/repository/maven-public/") }
maven { url = uri("https://jitpack.io") }
maven {
url = uri("https://maven.pkg.github.com/skycavemc/skycavelib")
credentials {
username = localProperties.getProperty("gpr.user")
password = localProperties.getProperty("gpr.key")
}
}
}
dependencies {
implementation(kotlin("stdlib"))
compileOnly("io.papermc.paper:paper-api:1.19.2-R0.1-SNAPSHOT")
implementation("de.skycave:skycavelib:1.0.2")
}
java {
toolchain.languageVersion.set(JavaLanguageVersion.of(17))
}
I also made sure I have a file named local.properties in my project where I set gpr.user and gpr.key correctly. The authentication works and the library is downloaded and indexed. IntelliJ also shows the library under "External Libraries".
When I try to use a class from that library, IntelliJ's autocompletion suggests the correct import. But after importing it, IntelliJ says "Unresolved reference" in the line of the import and the line where I use that class.
However, the gradle build still succeeds. Also, I only experience this issue when I import something from that library in a Kotlin class. In a Java class, IntelliJ can resolve the reference. This problem does not only happen in one specific project, but in all projects where I try to import something from that library, which means it's probably not an issue with the project configuration. The other Java library I use (paper-api) works fine when importing in both Kotlin and Java files. Invalidating caches and reloading all gradle projects has not solved the issue.
I suppose there is something misconfigured in my library https://github.com/skycavemc/skycavelib. Does someone have an idea what could have went wrong there? This is my build.gradle for the library I am trying to import from:
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.7.10'
id 'com.github.johnrengelman.shadow' version '7.1.2'
id 'maven-publish'
}
group = 'de.skycave'
version = '1.0.2'
def localProperties = new Properties()
localProperties.load(new FileInputStream(rootProject.file("local.properties")))
repositories {
mavenCentral()
maven {
name = 'papermc-repo'
url = 'https://repo.papermc.io/repository/maven-public/'
}
maven {
name = 'sonatype'
url = 'https://oss.sonatype.org/content/groups/public/'
}
maven {
name = 'jitpack'
url = 'https://jitpack.io'
}
}
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.7.10'
compileOnly 'io.papermc.paper:paper-api:1.19.2-R0.1-SNAPSHOT'
implementation 'org.mongodb:mongodb-driver-sync:4.7.1'
implementation 'com.google.code.gson:gson:2.9.1'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
implementation group: 'commons-io', name: 'commons-io', version: '2.11.0'
implementation 'com.github.heuerleon:mcguiapi:v1.3.5'
}
def targetJavaVersion = 17
java {
def javaVersion = JavaVersion.toVersion(targetJavaVersion)
sourceCompatibility = javaVersion
targetCompatibility = javaVersion
if (JavaVersion.current() < javaVersion) {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
}
manifest {
attributes 'Main-Class': "de.skycave.skycavelib.SkyCaveLib"
}
}
tasks.withType(JavaCompile).configureEach {
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
//noinspection GroovyAssignabilityCheck, GroovyAccessibility
options.release = targetJavaVersion
}
}
processResources {
def props = [version: version]
inputs.properties props
filteringCharset 'UTF-8'
filesMatching('plugin.yml') {
expand props
}
}
build {
dependsOn(shadowJar)
}
shadowJar {
archiveFileName.set("${project.name}-${project.version}.jar")
}
publishing {
repositories {
maven {
name = "GitHubPackages"
url = "https://maven.pkg.github.com/skycavemc/skycavelib"
credentials {
username = localProperties.getProperty("gpr.user") ?: System.getenv("GITHUB_ACTOR")
password = localProperties.getProperty("gpr.token") ?: System.getenv("ACCESS_TOKEN")
}
}
}
publications {
library(MavenPublication) {
from components.java
}
}
}
Solution
I did some more research and found a hint that shadowed jars might not work well. I removed this part
build {
dependsOn(shadowJar)
}
from the build.gradle of my library and published it to the package repository. Everything works fine since then, seems like that was the issue.

Why does the Java compiler not find dependency modules in Gradle subprojects?

Exactly what the title says. For the record, I am using OpenJDK 15.0.1 and Gradle 6.7. I am trying to run code in a subproject with dependencies. When I try, I get a compiler error like so:
> Task :browser-core:compileJava FAILED
1 actionable task: 1 executed
(user profile)\IdeaProjects\cssbox-js-browser\browser-core\src\main\java\module-info.java:3: error: module not found: javafx.graphics
requires javafx.graphics;
^
(user profile)\IdeaProjects\cssbox-js-browser\browser-core\src\main\java\module-info.java:5: error: module not found: net.sf.cssbox
requires net.sf.cssbox;
^
(user profile)\IdeaProjects\cssbox-js-browser\browser-core\src\main\java\module-info.java:6: error: module not found: net.sf.cssbox.jstyleparser
requires net.sf.cssbox.jstyleparser;
^
As far as I'm concerned, the dependencies in question (JavaFX, CSSBox) are already specified under the root build.gradle file. Why does the compiler overlook these dependencies, and how do I fix it?
For reference, here's my root build.gradle:
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
java {
modularity.inferModulePath = true
}
allprojects {
plugins.withType(JavaPlugin, {
dependencies {
//determine dependency names
def os = org.gradle.internal.os.OperatingSystem.current()
def fxDep = ""
if (os.isWindows()) {
fxDep = "win"
}
else if (os.isMacOsX()) {
fxDep = "mac"
}
else if (os.isLinux()) {
fxDep = "linux"
}
//implementation 'org.slf4j:slf4j-jdk14:1.7.30'
implementation 'org.slf4j:slf4j-nop:1.7.30'
implementation('net.sf.cssbox:cssbox:5.0.0') {
exclude group: 'xml-apis', module: 'xml-apis'
}
implementation "org.openjfx:javafx-base:15.0.1:${fxDep}"
implementation "org.openjfx:javafx-controls:15.0.1:${fxDep}"
implementation "org.openjfx:javafx-graphics:15.0.1:${fxDep}"
implementation "org.openjfx:javafx-fxml:15.0.1:${fxDep}"
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.1'
}
})
}
test {
useJUnitPlatform()
}
and the subproject's build.gradle:
plugins {
id 'application'
}
group 'io.github.jgcodes'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
test {
useJUnitPlatform()
}
It turns out that
java {
modularity.inferModulePath = true;
}
needs to be set for all subprojects individually. Specifically, you need to place it in the allprojects closure.

Adding support for Kotlin sources to existing Java multi-project Gradle build

I have a Spring Boot Java project that builds using Gradle (v6.2.2).
build.gradle.kts
plugins {
base
java
id("org.springframework.boot") apply false
}
val gradleVersionProperty: String by project
val javaVersion: String by project
val springBootVersion: String by project
val springCloudStarterParentBomVersion: String by project
if (JavaVersion.current() != JavaVersion.VERSION_11) {
throw GradleException("This build must be run with JDK 11")
} else {
println("Building with JDK " + JavaVersion.current())
}
tasks.withType<Wrapper> {
gradleVersion = gradleVersionProperty
distributionType = Wrapper.DistributionType.ALL
}
allprojects {
group = "com.meanwhile.in.hell"
version = "$version"
// Repos used in dependencyManagement section of settings.gradle
repositories {
mavenLocal()
mavenCentral()
maven("https://repo.spring.io/snapshot")
maven("https://repo.spring.io/milestone")
}
}
subprojects {
if (!project.name.startsWith("platform")) {
apply {
plugin("java-library")
}
java.sourceCompatibility = JavaVersion.VERSION_11
java.targetCompatibility = JavaVersion.VERSION_11
// Change the default test logging settings
tasks.withType<Test>() {
useJUnitPlatform()
testLogging {
events = setOf(
org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED,
org.gradle.api.tasks.testing.logging.TestLogEvent.PASSED,
org.gradle.api.tasks.testing.logging.TestLogEvent.SKIPPED
)
exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
}
enableAssertions = false
ignoreFailures = gradle.startParameter.isContinueOnFailure
maxParallelForks =
(Runtime.getRuntime().availableProcessors() / 2).takeIf { it > 0 } ?: 1
}
dependencies {
"api"(enforcedPlatform("org.springframework.boot:spring-boot-dependencies:$springBootVersion"))
"api"(enforcedPlatform("org.springframework.cloud:spring-cloud-dependencies:$springCloudStarterParentBomVersion"))
"implementation"(enforcedPlatform(project(":platform-dependencies")))
"testCompile"("org.springframework.boot:spring-boot-starter-test")
}
}
}
However, I would like to add support for Spring Boot Kotlin sub-projects within it. I have used a very simple sample project from a Kotlin-only project I have that builds fine within it. Without any changes to my root build.gradle.kts file, my current build error is:
* What went wrong:
Execution failed for task ':kotlin-sample-project:bootJar'.
> Main class name has not been configured and it could not be resolved
I have not configured the main class for any of the Java sub-projects and neither have I in my Kotlin-only other project.
My build.gradle.kts in kotlin-sample-project is very simple:
plugins {
id("org.springframework.boot")
}
dependencies {
implementation("org.springframework.cloud:spring-cloud-starter-gateway")
}
And my main class looks like:
src/main/kotlin/sample/KotlinSampleApplication.kts
package com.meanwhile.in.hell.kotlinsample
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
#SpringBootApplication
open class KotlinSampleApplication
fun main(args: Array<String>) {
runApplication<KotlinSampleApplication>(*args)
}
I have tried to add the kotlin plugin, but the build fails instantly not knowing what it is.
plugins {
base
java
kotlin
}
Error:
Line 9: kotlin
^ Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val <T : Any> Class<TypeVariable(T)>.kotlin: KClass<TypeVariable(T)> defined in kotlin.jvm
I have tried to add the kotlin plugin, but the build fails instantly not knowing what it is.
It should be:
build.gradle.kts:
plugins {
kotlin("jvm").version("1.3.72")
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
}
Bot Kotlin JVM plugin should be applied and Kotlin stdlib be present on compile classpath.

Kotlin+Gradle runnable jar - dependency causing "Could not find or load main class"

Gradle build file:
buildscript {
ext.kotlin_version = '1.2.41'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
group 'com.anivive'
version '0.1'
apply plugin: 'kotlin'
sourceSets {
main.java.srcDirs += 'src/main/kotlin/'
test.java.srcDirs += 'src/test/kotlin/'
}
repositories {
mavenLocal()
maven {
url "https://packagecloud.io/anivive/anivive/maven2"
}
mavenCentral()
}
dependencies {
compile 'anivive:Import_Utils:1.2.44'
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
jar {
baseName = 'XMLModelBuilder'
version = '0.1'
manifest {
attributes 'Main-Class': 'com.anivive.Main'
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
File structure:
src
- main
- kotlin
- com
- anivive
- Main.kt
Main.kt:
package com.anivive
import com.anivive.util.ExampleClass
object Main {
#JvmStatic
fun main(args: Array<String>) {
ExampleClass.exampleMethod()
}
}
So, I'm trying to build a runnable jar file that will call a single method from a class in the dependency 'anivive:Import_Utils:1.2.44'.
If I remove the dependency, and change my main method to just println("Test"), the jar will run fine via java -jar build/libs/jarFile.jar and it will print out Test.
However, with the dependency included and when trying to call a function from it, I will get Error: Could not find or load main class com.anivive.Main whenever I try to run the Jar file. I suspect it has something to do with hosting the jar file on packagecloud, but I'm surprised this is a problem, considering I can run the program just fine from IntelliJ.
What gives?

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?
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
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
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.
This plugin worked for me (gradle 5.6):
plugins {
id 'java'
id "io.freefair.aspectj.post-compile-weaving" version "4.1.4"
}
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() {
}
}
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.

Categories

Resources