Aspectj: intercept method from external jar

懵懂的女人 提交于 2019-11-27 16:09:23

问题


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


回答1:


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).




回答2:


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>


来源:https://stackoverflow.com/questions/11292352/aspectj-intercept-method-from-external-jar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!