Reputation: 1127
I would like to use initialization with aspectj.
@Aspect
public class TotoAspect
{
@Before("initialization( *.new(..))")
public void test(JoinPoint thisJoinPoint) throws AuditReactiveException
{
System.err.println("I AM HERE");
}
}
But, the message was not print with
new ABC();
I use the java agent for aspectj.
Where is the mistake ?
Upvotes: 1
Views: 4598
Reputation: 67317
Well, actually on your console you should see something like this:
Exception in thread "main" org.aspectj.lang.NoAspectBoundException: Exception while initializing de.scrum_master.aspect.TotoAspect: org.aspectj.lang.NoAspectBoundException: de.scrum_master.aspect.TotoAspect
at de.scrum_master.aspect.TotoAspect.aspectOf(TotoAspect.java:1)
at de.scrum_master.app.ABC.<init>(ABC.java:4)
at de.scrum_master.app.ABC.main(ABC.java:10)
Caused by: org.aspectj.lang.NoAspectBoundException: de.scrum_master.aspect.TotoAspect
at de.scrum_master.aspect.TotoAspect.aspectOf(TotoAspect.java:1)
at de.scrum_master.aspect.TotoAspect.<init>(TotoAspect.java:10)
at de.scrum_master.aspect.TotoAspect.ajc$postClinit(TotoAspect.java:1)
at de.scrum_master.aspect.TotoAspect.<clinit>(TotoAspect.java:1)
... 2 more
This is because your advice is targetting all constructors, even its own aspect's one. You need to exclude it. Here is a compileable code sample:
Exception class:
This is to demonstrate that your pointcut also matches the exception's constructor.
package de.scrum_master.app;
public class AuditReactiveException extends Exception {
public AuditReactiveException(String message) {
super(message);
}
}
Sample driver class with main method:
package de.scrum_master.app;
public class ABC {
public ABC() throws AuditReactiveException {
System.err.println("Creating ABC object");
throw new AuditReactiveException("Something went wrong");
}
public static void main(String[] args) throws AuditReactiveException {
new ABC();
}
}
Aspect with modified pointcut:
package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import de.scrum_master.app.AuditReactiveException;
@Aspect
public class TotoAspect {
@Before("initialization(*.new(..)) && !within(TotoAspect)")
public void test(JoinPoint thisJoinPoint) throws AuditReactiveException {
System.err.println(thisJoinPoint);
}
}
Sample output:
initialization(de.scrum_master.app.ABC())
Creating ABC object
initialization(de.scrum_master.app.AuditReactiveException(String))
Exception in thread "main" de.scrum_master.app.AuditReactiveException: Something went wrong
at de.scrum_master.app.ABC.<init>(ABC.java:6)
at de.scrum_master.app.ABC.main(ABC.java:10)
You might also want to exclude the exception constructor, i.e. you should narrow down the pointcut's scope with package and/or class names. Check out the AspectJ documentation for pointcut syntax description, e.g. how to use jokers like *
or ..
.
Upvotes: 10