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.
Related
I am beating against a wall for a whole week. I can't really see the reason why it doesn't work. I have a project where I want to run my Java project with the following build.gradle config:
plugins {
id 'java'
id 'org.springframework.boot' version '2.6.3'
id("io.spring.dependency-management") version "1.0.11.RELEASE"
id 'org.web3j' version "4.8.4"
}
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
mavenCentral()
jcenter()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
group = 'com.suplab'
sourceSets {
main {
solidity {
srcDir "contracts"
}
}
test {
solidity {
srcDir "contracts"
}
}
}
ext {
web3jVersion = '4.8.4'
}
npmInstall {
enabled false
}
dependencies {
implementation "org.web3j:core:$web3jVersion"
implementation "org.web3j:web3j-evm:$web3jVersion"
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.hibernate:hibernate-core:5.6.5.Final'
}
I use gradle version 6.8, since it was specified by developer of the plugin. When I try to build this project from the parent, root folder that is the root of the project, it fails with following error:
A problem occurred configuring project ':api'.
> Failed to notify project evaluation listener.
> Task with name 'resolveSolidity' not found in project ':api'.
> Could not create task ':api:generateTestContractWrappers'.
> Task with name 'compileTestSolidity' not found in project ':api'.
I can't figure it out. I checked it against the build that being generated with web3j-cli, and it's the same for the configuration property (both configs have it blank). So, I don't see any reason WHY it fails. Here's the webj3-cli generated build file:
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.3.61'
id 'application'
id "com.github.johnrengelman.shadow" version "5.2.0"
id 'org.web3j' version '4.8.4'
}
group 'org.web3j'
version '0.1.0'
sourceCompatibility = 1.8
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
mavenCentral()
jcenter()
}
web3j {
generatedPackageName = 'org.web3j.generated.contracts'
excludedContracts = ['Mortal']
}
ext {
web3jVersion = '4.8.4'
logbackVersion = '1.2.3'
}
dependencies {
implementation "org.web3j:core:$web3jVersion",
"ch.qos.logback:logback-core:$logbackVersion",
"ch.qos.logback:logback-classic:$logbackVersion"
implementation "org.web3j:web3j-unit:$web3jVersion"
implementation "org.web3j:web3j-evm:$web3jVersion"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1'
}
jar {
manifest {
attributes(
'Main-Class': 'org.web3j.Web3App',
'Multi-Release':'true'
)
}
}
application {
mainClassName = 'org.web3j.Web3App'
}
test {
useJUnitPlatform()
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
I am trying to run the test for java applications (with module system enabled) using Gradle and getting the following error.
java.lang.IllegalAccessError: class org.junit.platform.launcher.core.LauncherFactory (in unnamed module #0x7cd3a5) cannot access class org.junit.platform.commons.util.Preconditions (in module org.junit.platform.commons) because module org.junit.platform.commons does not export org.junit.platform.commons.util to unnamed module #0x7cd3a5
Error says module org.junit.platform.commons does not export org.junit.platform.commons.util
This is how my build file looks like:
import org.springframework.boot.gradle.plugin.SpringBootPlugin
plugins {
id 'java'
id 'org.springframework.boot' version '2.3.1.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id "org.beryx.jlink" version "2.21.0"
id "org.javamodularity.moduleplugin" version "1.6.0"
}
repositories {
gradlePluginPortal()
jcenter()
}
sourceCompatibility = JavaVersion.VERSION_14
targetCompatibility = JavaVersion.VERSION_14
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
jar {
enabled = true;
}
application{
mainModule='com.sudhir.registration'
}
test {
useJUnitPlatform()
}
configurations {
springFactoriesHolder { transitive = false }
}
dependencyManagement {
imports {
mavenBom SpringBootPlugin.BOM_COORDINATES
}
}
dependencies {
springFactoriesHolder 'org.springframework.boot:spring-boot-actuator-autoconfigure'
springFactoriesHolder 'org.springframework.boot:spring-boot-autoconfigure'
springFactoriesHolder 'org.springframework.boot:spring-boot'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
exclude group: 'com.vaadin.external.google', module: 'android-json'
}
}
mainClassName = "com.sudhir.registration.ApiApplication"
prepareMergedJarsDir.doLast {
// extract and merge META-INF/spring.factories from springFactoriesHolder
def factories = configurations.springFactoriesHolder.files.collect {
def props = new Properties()
props.load(zipTree(it).matching { include 'META-INF/spring.factories' }.singleFile.newInputStream())
props
}
def mergedProps = new Properties()
factories.each { props ->
props.each { key, value ->
def oldVal = mergedProps[key]
mergedProps[key] = oldVal ? "$oldVal,$value" : value
}
}
def content = mergedProps.collect { key, value ->
def v = (value as String).replace(',', ',\\\n')
"$key=$v"
}.join('\n\n')
mkdir("$jlinkBasePath/META-INF")
new File("$jlinkBasePath/META-INF/spring.factories").text = content
// insert META-INF/spring.factories into the main jar
ant.zip(update: "true", destfile: jar.archivePath, keepcompression: true) {
fileset(dir: "$jlinkBasePath", includes: 'META-INF/**')
}
}
jlink {
imageZip = file("$buildDir/image-zip/registration-service-image.zip")
options = ['--strip-java-debug-attributes', '--compress', '2', '--no-header-files', '--no-man-pages']
forceMerge 'jaxb-api', 'byte-buddy', 'classgraph'
mergedModule {
uses 'ch.qos.logback.classic.spi.Configurator'
excludeRequires 'com.fasterxml.jackson.module.paramnames'
excludeProvides implementation: 'com.sun.xml.bind.v2.ContextFactory'
excludeProvides servicePattern: 'javax.enterprise.inject.*'
excludeProvides service: 'org.apache.logging.log4j.spi.Provider'
excludeProvides servicePattern: 'reactor.blockhound.integration.*'
}
launcher {
name = 'run'
jvmArgs = [
'--add-reads', 'registration.service.merged.module=com.sudhir.registration',
'-cp', 'config/',
]
}
}
tasks.jlink.doLast {
copy {
from "src/main/resources"
into "$imageDir.asFile/bin/config"
}
copy {
from "$buildDir/classes/java/main/com/sudhir/registration"
into "$imageDir.asFile/bin/config/com/sudhir/registration/for-spring-classpath-scanner"
}
}
However, I am able to run specific tests in IntelliJ. I think it's because Intellij is using classpath instead of module path.
I am using gradle-module-system plugin to build, test and run. sample code can be found here.
Can someone please assist me how to deal with this issue. I am very new to using java module system.
Not quite sure on the reason of this problem. These threads may help to understand it: this, this, this or this
But this is what helped me in a similar case:
test {
moduleOptions {
runOnClasspath = true
}
useJUnitPlatform()
}
(Adding moduleOptions setting to the test task)
The generated protobuf class is under generated-sources as expected.
But it has references to com.google.protobuf, for example below code. And I get compilation error saying com.google.protobuf not found.
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
The below is my build.gradle file.
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
id 'com.google.protobuf' version '0.8.10'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
sourceSets {
main {
proto {
srcDir 'src/main/proto'
}
java {
// include self written and generated code
srcDirs 'src/main/java', 'generated-sources/main/java'
}
}
// remove the test configuration - at least in your example you don't have a special test proto file
}
protobuf {
// Configure the protoc executable
protoc {
// Download from repositories
artifact = 'com.google.protobuf:protoc:3.0.0'
}
generateProtoTasks.generatedFilesBaseDir = 'generated-sources'
generateProtoTasks {
// all() returns the collection of all protoc tasks
all().each { task ->
// Here you can configure the task
}
// In addition to all(), you may get the task collection by various
// criteria:
// (Java only) returns tasks for a sourceSet
ofSourceSet('main')
}
}
I think the problem is that the protobuf library is not showing up in the external libraries of my intellij project. Is there a way to make it work with gradle?
Working gradle file:
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
id 'com.google.protobuf' version '0.8.10'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'com.google.protobuf:protobuf-java:3.11.1'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
sourceSets {
main {
proto {
srcDir 'src/main/proto'
}
java {
// include self written and generated code
srcDirs 'src/main/java', 'generated-sources/main/java'
}
}
// remove the test configuration - at least in your example you don't have a special test proto file
}
protobuf {
// Configure the protoc executable
protoc {
// Download from repositories
artifact = 'com.google.protobuf:protoc:3.6.0'
}
generateProtoTasks.generatedFilesBaseDir = 'generated-sources'
generateProtoTasks {
// all() returns the collection of all protoc tasks
all().each { task ->
// Here you can configure the task
}
// In addition to all(), you may get the task collection by various
// criteria:
// (Java only) returns tasks for a sourceSet
ofSourceSet('main')
}
}
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
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.