Aspects with Annotations

Problem

Define a pointcut for annotated methods. The most example are based only on @within or @annotation which has the downside that the aspect is added to all methods and the check of the annotation is executed during runtime.

Solution

@Aspect
@Component
public class MethodAspect {
    /**
     * This ensures that the aspect is only woven into methods with the annotation.
     * Otherwise all methods are woven!
     */
    @Pointcut("execution(@MethodAnnotation * * (..))")
    private void isAnnotated() {};
    /**
     * (optional) Limit package scan to our project only
     */
    @Pointcut("execution(* your.project.package..*(..))")
    private void isInPackage() {};

    @Around("isAnnotated() && isInPackage() && @annotation(annotation)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint, 
                                   MethodAnnotation annotation) throws Throwable {
        return joinPoint.proceed();
    }
}

Git Repository

https://github.com/sterlp/training/tree/master/aspect

Links

Paul Sterl has written 52 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>