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

问题描述

我已经使用Spring AOP / 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?

解决方法

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

@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而没有捕获ThrowableError个不会被记录。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...