一整天我都在尝试使用 AspectJ - 添加依赖项、安装插件、创建 .aj 文件或使用 @Aspect 注释进行标记,但在 gradle 上似乎没有任何效果。请帮助我理解我的问题。
我的 GreetingAspect.aj 文件
package org.example;
public aspect GreetingAspect {
pointcut greeting() : execution(* Main.printName(..));
before() : greeting() {
System.out.print("Hello ");
}
}
代码应该在 .printName() 的每个实例之前打印“Hello (name)”,这样我就可以看到“pointcut”和“before”正在工作
plugins {
id 'java'
id "io.freefair.aspectj" version "8.3"
}
group = 'org.example'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation platform('org.junit:junit-bom:5.9.1')
testImplementation 'org.junit.jupiter:junit-jupiter'
runtimeOnly 'org.aspectj:aspectjweaver:1.9.7'
runtimeOnly 'org.aspectj:aspectjrt:1.9.7'
implementation 'org.aspectj:aspectjtools:1.9.7'
}
test {
useJUnitPlatform()
}
package org.example;
public class Main {
public static void main(String[] args) {
printName("Max");
printName("John");
printName("Martin");
}
public static void printName(String name) {
System.out.println(name);
}
}
我尝试: 从市场安装 AspectJ 插件,增加了对 .aj 的支持,但它们似乎什么也没做, 从 https://plugins.gradle.org/ 安装 AspectJ 插件, 直接在lib中安装.jar, 将版本从 1.9.10 更改为 1.9.7, 使用 .java 类而不是 .aj 使用 @Aspect 注释。
也许您在 src/main/java 中都有两个源文件,或者只有 src/main/aspectj 中的切面,但在默认配置中,Frefair 希望所有源文件都位于 src/main/aspectj 中:
然后,该项目完美运行。
[可选] 不过,您也可以稍微简化 Gradle 构建配置,并将 AspectJ 更新到更新的版本,因为 1.9.7 仅支持 Java 16,但 1.9.20 最高支持 Java 20。
plugins {
id 'java'
id "io.freefair.aspectj" version "8.3"
}
group = 'org.example'
version = '1.0-SNAPSHOT'
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
testImplementation platform('org.junit:junit-bom:5.9.1')
testImplementation 'org.junit.jupiter:junit-jupiter'
implementation 'org.aspectj:aspectjrt:1.9.20'
}
test {
useJUnitPlatform()
}