Guice 中基于 AOP 的日志记录

Ank*_*jan 2 java logging aop aspectj guice

我正在尝试在 Google - Guice 中实现基于 AOP 的日志记录。我已经用过MethodInterceptor这个但它不起作用。我在 Spring 中通过定义切入点来使用相同的方法。那里一切都运转良好。

基于 AOP 的日志记录的 Spring 代码 -

@Aspect
public class LoggingAspect {

 private static Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

   @Around("requiredLog()")
   public Object bentoBoxAround(ProceedingJoinPoint proceedingJoinPoint) {

      Object returnValue = null;
      try {

          logger.info("Entered into the method -> " + proceedingJoinPoint.getSignature().toShortString()
                  + " and input arguments are -> " + Arrays.asList(proceedingJoinPoint.getArgs()));
          returnValue = proceedingJoinPoint.proceed();
          logger.info("Method Execution over !! " + proceedingJoinPoint.getSignature().toShortString());
      } catch (Throwable e) {
          logger.error("Method has an exception " + e.getMessage());
      }
      return returnValue;
   }

   @Pointcut("within(org.cal.bento..*)")
   public void allRequiredPakageLog() {
   }

 }
Run Code Online (Sandbox Code Playgroud)

从上面的代码我们可以记录包内所有类和方法的执行org.cal.bento.*

基于 AOP 的日志记录的 Guice 代码-

public class GuiceLoggingInterceptor implements MethodInterceptor {

 private static Logger logger = LoggerFactory
 .getLogger(GuiceLoggingInterceptor.class);

  @Override
  public Object invoke(MethodInvocation invocation) throws Throwable {
    Object returnValue = null;
    try {
        logger.info("GUICE - Entered into the method -> " + invocation.getMethod().getName()
                    + " and input arguments are -> " + Arrays.asList(invocation.getArguments()));
        returnValue = invocation.proceed();
        logger.info("Method Execution over !! " + invocation.getMethod().getName());
    } catch (Throwable e) {
        logger.error("GUICE - Method has an exception " + e.getMessage());
    }
    return returnValue;
  }
}
Run Code Online (Sandbox Code Playgroud)

绑定类 -

public class GuiceAopModule extends AbstractModule {

  @Override
  protected void configure() {
      bindInterceptor(Matchers.any(), Matchers.any(), new GuiceLoggingInterceptor());
  }
}
Run Code Online (Sandbox Code Playgroud)

我们可以在 Guice 中做类似的日志记录吗(通过为整个日志系统仅定义一个基于 Aspect 的类)。我不想修改每个类。

参考教程 - https://schakrap.wordpress.com/2009/07/30/method-entry-exit-logging-in-guice-with-aop/

任何帮助将不胜感激。

pan*_*adb 5

您的问题似乎是您没有使用 guice 进行创建。来自 guice 文档:

这种方法对可以拦截的类和方法施加了限制:

[...]

实例必须由 Guice 通过 @Inject 注释或无参数构造函数创建。 不可能对不是由 Guice 构造的实例使用方法拦截。

所以这意味着,因为您的实例是由 spring 创建的,并且可能添加到 guice,所以 guice 没有机会代理这些类进行拦截。

来源:

https://github.com/google/guice/wiki/AOP

编辑:

为了能够完成这项工作,您可以做的(作为解决方法)是:

  1. Spring 创建您的实例。

  2. 把它们放入guice中

  3. 创建一个由 Guice 创建的委托对象,并将 (1) 的 bean 注入到包装器中。

  4. 使用包装器而不是1中的对象,然后方法将被拦截。