简体   繁体   中英

AspectJ weaving for private methods

I've got an AspectJ weaving annotation that works for public methods, but private method are being ignored. The purpose of this method is to simply log the time it took to run the function.

@Aspect
@Slf4j
public class TimedLogAspect {

    @Pointcut("@annotation(timedLogVar)")
    public void annotationPointCutDefinition(TimedLog timedLogVar) {}

    @Pointcut("execution(* *(..))")
    public void atExecution() {}

    @Around(value = "annotationPointCutDefinition(timedLogVar) && atExecution()", argNames = "joinPoint,timedLogVar")
    public Object around(ProceedingJoinPoint joinPoint, TimedLog timedLogVar) throws Throwable {
        Stopwatch stopwatch = Stopwatch.createStarted();
        Object returnValue = joinPoint.proceed();
        stopwatch.stop();

        MessageBuilder messageBuilder = new MessageBuilder(joinPoint.toShortString(), stopwatch.elapsed(TimeUnit.MILLISECONDS))
                .attachMessage(timedLogVar.message())
                .attachMethodArgs(timedLogVar.shouldAttachMethodArgs(), Stream.of(joinPoint.getArgs()).collect(Collectors.toList()))
                .attachReturnValue(timedLogVar.shouldAttachReturnValue(), returnValue);

        log.info(messageBuilder.build(), messageBuilder.getArgs().toArray());

        return returnValue;
    }
}

with this being the actual interface:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TimedLog {
    boolean shouldAttachMethodArgs() default false;
    boolean shouldAttachReturnValue() default false;
    String message() default "";
}

I've seen a lot of answer, being adding private before the first * in the execution portion, I've seen privileged which isn't supported for annotations, and I'm using AspectJ with no SpringAOP.

any ideas?

The answer is simple: use native AspectJ syntax. You mentioned it by yourself. You even said that you use full AspectJ, not Spring AOP. So switching should not be a problem.

You have lots of advantages:

  • more power (some features are unavailable in annotation syntax, as you noticed),
  • syntax highlighting and code completion in IDEs,
  • more expressive syntax (less verbose and more elegant, ie no need to bind thisJoinPoint in advices and easier use of if() , no need for fully-qualified class names because you can just import them).

The annotation-based syntax IMO is just terribly difficult to read, everything is in a single string inside an annotation parameter. I only use it if I have no other choice or when answering questions about it here.

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