I am using a X.jar and adding to my AspectJ project(in eclipse). I have written pointcut and advice for a method myMethod() inside X.jar.
But aspectj is not intercepting this method call.
How can I tell aspectj to intercept method calls on external jars.Or is it not possible?
Thanks
There are two options:
a) compile the aspects into the JAR
b) use load time weaving (I'd go with that one)
Both of these are advanced topics, I'd suggest you read AspectJ in Action (2nd Ed) by Ramnivas Laddad to learn more.
To clarify: there are different types of pointcuts. If your code calls the library's methods, you can of course intercept these calls, as they happen in your code. So call()
pointcuts will work, but execute()
(and many other) pointcuts won't because they change the executing method, which is not in your code base. So you have to either change the byte code of the library (option a) or change how it is loaded into your application (option b).
Here is a simple example with AspectJ Load-Time Weaving on GitHub https://github.com/medvedev1088/aspectj-ltw-example
It uses Joda Time library to demonstrate how to intercept the DateTime#toString() method invocations.
The aspect:
@Aspect
public class DateTimeToStringAspect {
public static final String TO_STRING_RESULT = "test";
@Pointcut("execution(* org.joda.time.base.AbstractDateTime.toString())")
public void dateTimeToString() {
}
@Around("dateTimeToString()")
public Object toLowerCase(ProceedingJoinPoint joinPoint) throws Throwable {
Object ignoredToStringResult = joinPoint.proceed();
System.out.println("DateTime#toString() has been invoked: " + ignoredToStringResult);
return TO_STRING_RESULT;
}
}
aop.xml
<aspectj>
<aspects>
<!-- Aspects -->
<aspect name="com.example.aspectj.DateTimeToStringAspect"/>
</aspects>
<weaver options="-verbose -showWeaveInfo">
<include within="org.joda.time.base.AbstractDateTime"/>
</weaver>
</aspectj>
test:
public class DateTimeToStringAspectTest {
@Test
public void testDateTimeToString() throws Exception {
assertThat(new DateTime().toString(), is(DateTimeToStringAspect.TO_STRING_RESULT));
}
}
Surefire plugin configuration from pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<argLine>-XX:-UseSplitVerifier</argLine>
<argLine>-javaagent:${user.home}/.m2/repository/org/aspectj/aspectjweaver/${aspectjweaver.version}/aspectjweaver-${aspectjweaver.version}.jar</argLine>
</configuration>
</plugin>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With