简体   繁体   中英

Spring Boot and AspectJ — Can I intercept a call to the java.util.ArrayList.size() method?

I'm learning about AOP using Spring Boot, and I feel I have a good handle on the concept. I'm able to intercept calls to methods I've created, but what about methods found within other libraries (such as "java.util.ArrayList.size()"). Can calls to these methods be intercepted too? If so, what would the aspect look like? I've tried the following aspect declaration, but I'm probably missing something here:

@Around(value = "execution(int java.util.ArrayList.size(..))")
    public void aroundListSize(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Before the size method is being invoked.");

        joinPoint.proceed();

        System.out.println("After the size method was invoked.");
    }

Spring AOP works with creating proxies around the advised classes. This has many limitations when compared to native AspectJ that directly modifies the bytecode of the advised classes. One of these limitations (among many others) is it only works with Spring managed beans, not any Java objects , like when using native AspectJ.

If your ArrayList objects are Spring managed beans, it will work to some extent, but you also need to be aware that the proxy based AOP mechanism only works through the advised class' external interface, so it will only work when invoked through the Spring provided proxy classes, and not when invoked through the this reference. So invoking this.method() from an advised class' anotherMethod() , it will not go through the proxy instance and the advice code will not be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM