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 {
}
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
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());
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With