Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading annotation property in aspect

How to read annotation property value in aspect?

I want my Around advice to be executed for all joint points annotated with @Transactional(readonly=false).

@Around("execution(* com.mycompany.services.*.*(..)) "
+ "&& @annotation(org.springframework.transaction.annotation.Transactional)")
public Object myMethod(ProceedingJoinPoint pjp) throws Throwable {
}
like image 706
Łukasz Koniecki Avatar asked Mar 23 '10 12:03

Łukasz Koniecki


2 Answers

You can do it without manual processing of signature, this way (argNames is used to keep argument names when compiled without debug information):

@Around(
    value = "execution(* com.mycompany.services.*.*(..)) && @annotation(tx)",
    argNames = "tx") 
public Object myMethod(ProceedingJoinPoint pjp, Transactional tx) 
    throws Throwable {
    ...
} 

See 7.2.4.6 Advice parameters

like image 176
axtavt Avatar answered Oct 22 '22 05:10

axtavt


You can do this this way:

Annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Profiled {
    public boolean showArguments();
}

Interceptor:

@Aspect
public class ProfilingAspect {

    public static Logger log = LoggerFactory.getLogger("ProfilingAspect");

    @Around("@annotation(profiled)")
    public Object profiled(final ProceedingJoinPoint pjp,
            final Profiled profiled) throws Throwable {
        StopWatch sw = new StopWatch();
        try {
            sw.start();
            return pjp.proceed();
        } finally {
            sw.stop();
            StringBuilder sb = new StringBuilder();
            sb.append("Method ");
            sb.append(pjp.getSignature().getName());
            if (profiled.showArguments()) {
                sb.append(" with arguments ");
                sb.append(Arrays.toString(pjp.getArgs()));
            }
            sb.append(" took ");
            sb.append(sw.getTime());
            sb.append(" millis");
            log.info(sb.toString());
        }
    }
}
like image 28
Daniel Jipa Avatar answered Oct 22 '22 05:10

Daniel Jipa