在方面中读取注释属性

时间:2010-03-23 12:10:31

标签: java spring aop aspectj

如何读取方面中的注释属性值?

我希望我的 围绕 建议针对所有使用 @Transactional(readonly = false) 注释的联合点执行

@Around("execution(* com.mycompany.services.*.*(..)) "
+ "&& @annotation(org.springframework.transaction.annotation.Transactional)")
public Object myMethod(ProceedingJoinPoint pjp) throws Throwable {
}

3 个答案:

答案 0 :(得分:5)

你可以在没有人工处理签名的情况下这样做(argNames用于在没有调试信息的情况下保存参数名称):

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

请参阅7.2.4.6 Advice parameters

答案 1 :(得分:3)

您必须在代码中执行此操作。例如

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
}

但你真的确定要搞乱交易处理吗?

答案 2 :(得分:3)

你可以这样做:

注释:

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

拦截器:

@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());
        }
    }
}