如何解决在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
而没有捕获Throwable
? Error
个不会被记录。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。