java—在guice应用程序中使用为spring应用程序编写的方面

68de4m5k  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(344)

我使用SpringAOP/aspectj注解编写了一个方面作为应用程序的一部分,类似于下面的方面:

@Aspect
@Component
public class LoggingAspect {
    @Around("@annotation(loggable)")
    public Object log(final ProceedingJoinPoint joinPoint, final Loggable loggable) throws Throwable {
        //log method arguments
        try {
            Object returnValue = joinPoint.proceed();
            // log return value
            return returnValue;
        } catch (Exception ex) {
            // publish exception metrics to some other system
            throw ex;
        }
    }
}

现在我想在另一个项目中使用这个方面,但是这个项目使用guice而不是spring。
我在读guice aop,它需要方面来实现methodinterceptor接口,因此我需要实现以下方法:

Object invoke(MethodInvocation methodInvocation) throws Throwable;

我想的是修改已经存在的方面来实现methodinterceptor并在内部调用log方法。如下所示:

@Aspect
@Component
public class LoggingAspect implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        // call already defined log method, but that method expects a ProceedingJoinPoint, however
        // I get MethodInvocation as input parameter in this method
    }

// already defined log method
@Around("@annotation(loggable)")
    public Object log(final ProceedingJoinPoint joinPoint, final Loggable loggable) throws Throwable {
......
.....
}

但由于两个方法之间的类型不兼容,我无法继续。
有没有一种方法可以重用现有的代码,而不是用重复的代码编写一个全新的方面来支持guice?

wwtsj6pe

wwtsj6pe1#

如果我理解正确,您希望反转控制流,这可以通过回调来完成。

@Aspect
@Component
class LoggingAspect implements MethodInterceptor {
    @Around("@annotation(loggable)")
    public Object log(final ProceedingJoinPoint joinPoint, final Loggable loggable) throws Throwable {
        return log(joinPoint::getArgs, () -> joinPoint.proceed(joinPoint.getArgs()));
    }

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        return log(methodInvocation::getArguments, methodInvocation::proceed);
    }

    public Object log(Supplier<Object[]> arguments, Supplier<Object[]> proceed) {
        Object[] args = arguments.get();
        //log method arguments
        try {
            Object returnValue = proceed.get();
            // log return value
            return returnValue;
        } catch (Exception ex) {
            // publish exception metrics to some other system
            throw ex;
        }
    }

}

顺便问一下,你是不是故意只钓 Exception 而不是 Throwable ? Error 不会记录。

相关问题