各种切入点表达式作用域意外触发多个建议调用

时间:2018-09-25 21:26:26

标签: java annotations aop aspectj pointcut

背景

使用方面进行记录,以使所有带有@Log批注的方法,类和构造函数均具有写入日志文件的信息。

问题

方法似乎被递归地称为一级深度,但是代码未显示任何此类递归关系。

实际

记录的结果:

2018-09-25 12:17:29,155 |↷|   EmailNotificationServiceBean#createPayload([SECURE])
2018-09-25 12:17:29,155 |↷|     EmailNotificationServiceBean#createPayload([{service.notification.smtp.authentication.password=password, mail.smtp.port=25, service.notification.smtp.authentication.username=dev@localhost, mail.mime.allowutf8=true, mail.smtp.auth=false, mail.smtp.starttls.enable=false, mail.smtp.timeout=10000, mail.smtp.host=localhost}])
2018-09-25 12:17:29,193 |↷|       EmailPayloadImpl#<init>([{service.notification.smtp.authentication.password=password, mail.smtp.port=25, service.notification.smtp.authentication.username=dev@localhost, mail.mime.allowutf8=true, mail.smtp.auth=false, mail.smtp.starttls.enable=false, mail.smtp.timeout=10000, mail.smtp.host=localhost}])
2018-09-25 12:17:29,193 |↷|         EmailPayloadImpl#validate([SECURE])
2018-09-25 12:17:29,194 |↷|           EmailPayloadImpl#validate([{service.notification.smtp.authentication.password=password, mail.smtp.port=25, service.notification.smtp.authentication.username=dev@localhost, mail.mime.allowutf8=true, mail.smtp.auth=false, mail.smtp.starttls.enable=false, mail.smtp.timeout=10000, mail.smtp.host=localhost}, SMTP connection and credentials])
2018-09-25 12:17:29,195 |↷|         EmailPayloadImpl#setMailServerSettings([SECURE])
2018-09-25 12:17:29,196 |↷|           EmailPayloadImpl#setMailServerSettings([{service.notification.smtp.authentication.password=password, mail.smtp.port=25, service.notification.smtp.authentication.username=dev@localhost, mail.mime.allowutf8=true, mail.smtp.auth=false, mail.smtp.starttls.enable=false, mail.smtp.timeout=10000, mail.smtp.host=localhost}])

预期

预期的记录结果:

2018-09-25 12:17:29,155 |↷|   EmailNotificationServiceBean#createPayload([SECURE])
2018-09-25 12:17:29,193 |↷|     EmailPayloadImpl#<init>([SECURE])
2018-09-25 12:17:29,193 |↷|       EmailPayloadImpl#validate([SECURE])
2018-09-25 12:17:29,195 |↷|       EmailPayloadImpl#setMailServerSettings([SECURE])

代码

日志记录方面:

@Aspect
public class LogAspect {
    @Pointcut("execution(public @Log( secure = true ) *.new(..))")
    public void loggedSecureConstructor() { }

    @Pointcut("execution(@Log( secure = true ) * *.*(..))")
    public void loggedSecureMethod() { }

    @Pointcut("execution(public @Log( secure = false ) *.new(..))")
    public void loggedConstructor() { }

    @Pointcut("execution(@Log( secure = false ) * *.*(..))")
    public void loggedMethod() { }

    @Pointcut("execution(* (@Log *) .*(..))")
    public void loggedClass() { }

    @Around("loggedSecureMethod() || loggedSecureConstructor()")
    public Object logSecure(final ProceedingJoinPoint joinPoint) throws Throwable {
        return log(joinPoint, true);
    }

    @Around("loggedMethod() || loggedConstructor() || loggedClass()")
    public Object log(final ProceedingJoinPoint joinPoint) throws Throwable {
        return log(joinPoint, false);
    }

    private Object log(final ProceedingJoinPoint joinPoint, boolean secure) throws Throwable {
        final Signature signature = joinPoint.getSignature();
        final Logger log = getLogger(signature);

        final String className = getSimpleClassName(signature);
        final String memberName = signature.getName();
        final Object[] args = joinPoint.getArgs();
        final CharSequence indent = getIndentation();
        final String params = secure ? "[SECURE]" : Arrays.deepToString(args);

        log.trace("\u21B7| {}{}#{}({})", indent, className, memberName, params);

        try {
            increaseIndent();

            return joinPoint.proceed(args);
        } catch (final Throwable t) {
            final SourceLocation source = joinPoint.getSourceLocation();
            log.warn("\u2717| {}[EXCEPTION {}] {}", indent, source, t.getMessage());
            throw t;
        } finally {
            decreaseIndent();
            log.trace("\u21B6| {}{}#{}", indent, className, memberName);
        }
    }

Log接口定义:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR})
public @interface Log {
    boolean secure() default false;
}

反编译的服务bean:

@Log
public class EmailNotificationServiceBean
implements EmailNotificationService {

    @Log(secure = true)
    @Override
    public EmailPayload createPayload(Map<String, Object> settings) throws NotificationServiceException {
        Map<String, Object> map = settings;
        JoinPoint joinPoint = Factory.makeJP((JoinPoint.StaticPart)ajc$tjp_2, (Object)this, (Object)this, map);
        Object[] arrobject = new Object[]{this, map, joinPoint};
        return (EmailPayload)LogAspect.aspectOf().logSecure(new EmailNotificationServiceBean$AjcClosure7(arrobject).linkClosureAndJoinPoint(69648));
    }

有效负载实现:

@Log
public class EmailPayloadImpl extends AbstractPayload implements EmailPayload {

    @Log(secure = true)
    public EmailPayloadImpl(final Map<String, Object> settings)
                    throws NotificationServiceException {
        validate(settings, "SMTP connection and credentials");
        setMailServerSettings(settings);
    }

    @Log(secure = true)
    private void validate(final Map<String, Object> map, final String message)
                    throws NotificationServiceException {
        if (map == null || map.isEmpty()) {
            throwException(message);
        }
    }

    @Log(secure = true)
    private void setMailServerSettings(final Map<String, Object> settings) {
        this.mailServerSettings = settings;
    }

问题

造成的原因:

  • secure = true构造函数注释属性将被忽略;和
  • 要调用和记录两次validatesetMailServerSettings方法(安全一次,一次安全)?

我怀疑这些问题有关。

2 个答案:

答案 0 :(得分:2)

解决方案:

要解决重复问题,需要调整loggedClass()切入点定义:

@Pointcut("execution(* (@Log *) .*(..)) && !@annotation(Log)")
public void loggedClass() { }

请在其他信息部分中找到指向概念验证的链接。


说明:

与连接点(由@Pointcut注释定义)相关的问题,它们的模式相互交叉-这就是日志中重复的原因。

在我们的例子中,所有@Pointcut都具有足够的描述性,例如:

  • loggedClass()涵盖了@Log注释的类中的所有方法。
  • loggedSecureMethod()涵盖了@Log(secure = true)注释的所有方法。其他人与该人相似,因此我们忽略它们进行解释。

因此,如果EmailPayloadImpl@Log注释,而EmailPayloadImpl.validate()@Log(secure = true)注释-我们将有2个活动连接点:一个安全和一个非安全。这将导致添加2个日志条目。


假设我们要在注释中引入优先级,即方法级别的注释应覆盖类级别的注释-最简单的方法就是避免交叉连接点模式。

因此我们将需要3组方法:

  1. @Log(secure = true) = loggedSecureMethod()注释的方法
  2. @Log = loggedMethod()注释的方法
  3. 方法没有@Log批注,但是在带有@Log批注的类中,该方法是:

    @Pointcut("execution(* (@Log *) .*(..)) && !@annotation(Log)")
    public void loggedClass() { }
    

其他信息:

  1. 万一需要在类级别处理@Log(secure = true),当然需要添加类似于loggedClass()的附加连接点。
  2. GitHub
  3. 中添加了Proof of concept >>

答案 1 :(得分:1)

基本上,您的示例有两个问题,这些问题导致安全批注的重复和“忽略”。

首先,您在@Log中有一个EmailPayloadImpl类级注释和一个名为@Pointcut("execution(* (@Log *) .*(..))")的切入点loggedClass,它基本上将日志应用于所有类方法,包括构造函数。因此,这意味着对EmailPayloadImpl的任何方法调用都将以不安全的日志结尾,因为secure批注中false属性的默认值为Log

第二个问题是您的构造函数切入点不正确,这就是secure = true被忽略的原因。您使用的可见性关键字在为构造函数创建切入点时不正确。因此切入点

@Pointcut("execution(public @Log( secure = true ) *.new(..))")
public void loggedSecureConstructor() { }

应更改为

@Pointcut("execution(@Log( secure = true ) *.new(..))")
public void loggedSecureConstructor() { }

唯一的区别是删除了public可见性关键字。对loggedConstructor()应当执行相同的操作。

  

因此,当您构造函数切入点不正确时,@ Log注释会出现在   构造函数被忽略,因为没有切入点应该具有   用过的。而课堂上的@Log只是对所有   类方法,包括构造函数。

以您为例,您需要修复切入点并删除类级别的注释。

查看示例修复

让我们修复LogAspect中的切入点

@Aspect
public class LogAspect {
@Pointcut("execution(@Log( secure = true ) *.new(..))")
public void loggedSecureConstructor() { }

@Pointcut("execution(@Log( secure = true ) * *.*(..))")
public void loggedSecureMethod() { }

@Pointcut("execution(@Log( secure = false ) *.new(..))")
public void loggedConstructor() { }

@Pointcut("execution(@Log( secure = false ) * *.*(..))")
public void loggedMethod() { }

@Pointcut("execution(* (@Log *) .*(..))")
public void loggedClass() { }

@Around("loggedSecureMethod() || loggedSecureConstructor()")
public Object logSecure(final ProceedingJoinPoint joinPoint) throws Throwable {
    return log(joinPoint, true);
}

@Around("loggedMethod() || loggedConstructor() || loggedClass()")
public Object log(final ProceedingJoinPoint joinPoint) throws Throwable {
    return log(joinPoint, false);
}

private Object log(final ProceedingJoinPoint joinPoint, boolean secure) throws Throwable {
    final Signature signature = joinPoint.getSignature();
    final Logger log = getLogger(signature);

    final String className = getSimpleClassName(signature);
    final String memberName = signature.getName();
    final Object[] args = joinPoint.getArgs();
    final CharSequence indent = getIndentation();
    final String params = secure ? "[SECURE]" : Arrays.deepToString(args);

    log.trace("\u21B7| {}{}#{}({})", indent, className, memberName, params);

    try {
        increaseIndent();

        return joinPoint.proceed(args);
    } catch (final Throwable t) {
        final SourceLocation source = joinPoint.getSourceLocation();
        log.warn("\u2717| {}[EXCEPTION {}] {}", indent, source, t.getMessage());
        throw t;
    } finally {
        decreaseIndent();
        log.trace("\u21B6| {}{}#{}", indent, className, memberName);
    }
}

删除班级@Log批注

public class EmailPayloadImpl extends AbstractPayload implements EmailPayload {

@Log(secure = true)
public EmailPayloadImpl(final Map<String, Object> settings)
                throws NotificationServiceException {
    validate(settings, "SMTP connection and credentials");
    setMailServerSettings(settings);
}

@Log(secure = true)
private void validate(final Map<String, Object> map, final String message)
                throws NotificationServiceException {
    if (map == null || map.isEmpty()) {
        throwException(message);
    }
}

@Log(secure = true)
private void setMailServerSettings(final Map<String, Object> settings) {
    this.mailServerSettings = settings;
}