0

I want to use aspect in a method to log something, but I find it cannot trigger if it is an abstract class method.

I have tried both annotation based and execution, also use + for abstract class. However, all these does not work.

package com.sample.model;

@Data
@Builder
public class ProductBO {

    String product;

    String value;

}
package com.sample.handler;

public abstract class A {
    public abstract void process(Object request) throws Exception;
    ...
    ...
    protected ProductBO constructBO(String product, String value) {
        return RepaymentProductBO
                .builder()
                .product(product)
                .value(value)
                .build();
    }
    ...
}
package com.sample.txn.Posthandler;

@Component
public class B extends A {

    public abstract void process(Object request) throws Exception {

        ProductBO productBO = constructBO("VISA", "VI-123456,
                accountNumber);
    }
}
package com.sample.aspect;

@Aspect
@Component
public class TransactionAdvice {
    @Pointcut("execution(* com.sample.handler.A+.constructBO(..))")
    private void logData() {
    }

    @AfterReturning(pointcut = "logData()", returning = "result")
    @SuppressWarnings("unchecked")
    public void logData(JoinPoint joinPoint, Object result) {
        Object result = joinPoint.proceed();
        log("COME IN AfterReturning");
        if (result instanceof ProductBO) {
            System.out.println("Works...");
        }
    }
}

Update: If Spring AOP cannot work for this, I am wondering how to resolve it using AspectJ.

kriegaex
  • 63,017
  • 15
  • 111
  • 202
Wenkai Fan
  • 93
  • 1
  • 10
  • Internal method calls aren't intercepted as Spring uses proxies to apply AOP. – M. Deinum Jun 08 '21 at 14:10
  • Adding to M.Deinum's comment , please go through this [answer](https://stackoverflow.com/a/66635562/4214241) – R.G Jun 09 '21 at 00:54
  • @R.G hi thanks, but I am wondering if Aspectj can resolve this issue? – Wenkai Fan Jun 09 '21 at 01:22
  • @WenkaiFan yes it does. Unfortunately , I am not an expert with pure AspectJ. Please update the question with that requirement , you will defenitely get help – R.G Jun 09 '21 at 01:24
  • In AspectJ you can solve it with the same pointcut you are already using. Just give it a try. You only need to configure Spring to actually use AspectJ, most easily via load-time weaving as described in the [Spring manual](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-using-aspectj). Generic question, generic answer, sorry. I am going to close this one as a duplicate, linking to an answer explaining why self-invocation does not work in Spring AOP. Feel free to ask a new question if you have concrete problems with SpaectJ LTW. – kriegaex Jun 09 '21 at 02:17

0 Answers0