I am using the following sample code to understand AspectJ:
public class Account {
int balance = 20;
public boolean withdraw(int amount) {
if (balance < amount) {
return false;
}
balance = balance - amount;
return true;
}
public static void main(String[] args) {
Account acc = new Account();
acc.withdraw(5);
Account acc2 = new Account();
acc2.withdraw(25);
}
}
and the following Aspect:
public aspect AccountAspect {
pointcut callWithDraw(int amount, Account acc) :
call(boolean Account.withdraw(int)) && args(amount) && target(acc);
before(int amount, Account acc) : callWithDraw(amount, acc) {
System.out.printf("[before] withDraw, current balance %d%n", acc.balance);
}
boolean around(int amount, Account acc) : callWithDraw(amount, acc) {
if (acc.balance < amount) {
System.out.println("[around] withDraw, check failed");
return false;
}
System.out.println("[around] withDraw, check success");
return proceed(amount, acc);
}
after(int amount, Account acc) : callWithDraw(amount, acc) {
System.out.printf("[after] withDraw, current balance %d%n", acc.balance);
}
}
I am using the following Gradle build file:
plugins {
id 'java'
id "io.freefair.aspectj.post-compile-weaving" version "4.1.4"
}
configurations {
ajc
aspects
aspectCompile
compile{
extendsFrom aspects
}
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation group: 'org.aspectj', name: 'aspectjrt', version: '1.9.4'
implementation group: 'org.aspectj', name: 'aspectjweaver', version: '1.9.4'
implementation group: 'org.codehaus.mojo', name: 'aspectj-maven-plugin', version: '1.8'
testCompile group: 'junit', name: 'junit', version: '4.12'
}
compileJava {
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
//The following two lines are useful if you have queryDSL if not ignore
dependsOn configurations.ajc.getTaskDependencyFromProjectDependency(true, "compileJava")
}
and I am using Ajc compiler in Intellij to compile Java classes and aspects. In addition, I am setting the following VM options:
-javaagent:c:\\Users\\dev\\extlibs\\aspectjweaver-1.9.6.jar
The code compiles and runs without any issues but the aspect never triggers. I am not sure what I am missing in my configuration but I could not find anything else I can do when using AspectJ. If I use @Aspect annotation and register the annotated Aspect in META-INF/aop.xml, the aspect runs but annotated @Aspect Java classes does not allow to create privileged aspect which I need to catch/intercept a private method. Any suggestions on how to resolve this issue?