开发者

Reading annotation property in aspect

How to read annotation property value in aspect?

I want my Around advice to be executed for all j开发者_StackOverflowoint 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());
        }
    }
}


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜