5

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

我希望对使用@Transactional(readonly=false)注释的所有关节点执行我的Around建议。

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

3 回答 3

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 建议参数

于 2010-03-23T13:21:36.880 回答
5

你可以这样做:

注解:

@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());
        }
    }
}
于 2012-12-13T10:33:27.833 回答
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
}

但是你真的确定要搞乱事务处理吗?

于 2010-03-23T12:17:06.480 回答