我正在IntelliJ IDEA中基于Maven和AspectJ建立一个项目。不幸的是,所有尝试都失败了(即该方面似乎被忽略了)。
我使用maven文件创建了最小的测试项目。看起来像这样:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>com.nickwongdev</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.12.1</version>
<configuration>
<complianceLevel>11</complianceLevel>
<source>11</source>
<target>11</target>
<showWeaveInfo>true</showWeaveInfo>
<verbose>true</verbose>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<mainClass>de.benchmarktest.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
我必须使用aspectj-maven-plugin
中的com.nickwongdev
才能使用Java 11进行编译。
这个想法来自一个简单的Account
类的例子:
package de.benchmarktest;
public class Account {
int balance = 20;
public boolean withdraw(int amount) {
balance -= amount;
return true;
}
}
AccountAspect.aj
看起来像这样:
package de.benchmarktest;
public aspect AccountAspect {
pointcut callWithDraw(int amount, Account acc) :
call(boolean de.benchmarktest.Account.withdraw(int)) && args(amount) && target(acc);
boolean around(int amount, Account acc) :
callWithDraw(amount, acc) {
if (acc.balance < amount) return false;
return proceed(amount, acc);
}
}
如果我现在像这样构建示例主方法:
package de.benchmarktest;
public class Main {
public static void main(String[] args) {
Account acc = new Account();
System.out.println(acc.withdraw(10));
System.out.println(acc.withdraw(20));
}
}
我猜输出应该是true
,然后是false
。实际上,它是true
的两倍。因此,似乎没有触发Aspect。
如果通过mvn package
从控制台手动运行编译,则会得到[WARNING] No sources found skipping aspectJ compile
。我如何教系统在编译源代码时运行方面?预先感谢您的帮助!