5

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 {
}
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
Łukasz Koniecki
  • 564
  • 1
  • 6
  • 14

3 Answers3

7

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

axtavt
  • 239,438
  • 41
  • 511
  • 482
6

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());
        }
    }
}
Daniel Jipa
  • 878
  • 11
  • 24
3

you will have to do it in the code. For example

Signature s = pjp.getSugnature();
Method m = s.getDeclaringType().getDeclaredMethod(s.getName(), pjp.getArgs());
Transactional transactional = m.getAnnotation(Transactional.class);
if (transactional != null && !transactional.readOnly()) {
   // code
}

But are you really sure you want to mess with transaction handling?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140