2016-07-25 85 views
2

我正在尝试实现基于AOP的日志记录谷歌 - Guice。我为此使用了MethodInterceptor,但它不起作用。我在Spring中通过定义切点来使用它。一切工作都很好。基于AOP的登录Guice

基于Spring规范AOP日志 -

@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() { 
    } 

} 

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

基于AOP记录吉斯代码 -

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; 
    } 
} 

绑定类 -

public class GuiceAopModule extends AbstractModule { 

    @Override 
    protected void configure() { 
     bindInterceptor(Matchers.any(), Matchers.any(), new GuiceLoggingInterceptor()); 
    } 
} 

我们可以做类似的吉斯用于记录(通过定义为整个基础只是一个方面类记录系统)。我不想修改每个班级。

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

任何帮助将高度赞赏。

+0

“我为此使用了MethodInterceptor,但它不起作用”。什么是预期的输出? – CKing

+0

我想记录包中的所有方法执行。这段代码我使用的很好,但不会锁定日志文件中的任何日志。 –

+0

你的对象是如何创建的?只有在Guice创建你想拦截的所有实例时,Guice方法拦截才有效。 – pandaadb

回答

2

你的问题似乎是你没有使用guice进行创作。从吉斯文档:

这种方法对于哪些类和方法的限制可以 截获:

[...]

实例必须由吉斯通过创建@注入注解或 无参数构造函数对于非Guice构造的实例,不可能使用方法拦截 。

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

来源:

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

编辑:

你可以做什么(如解决方法)能够使这项工作将是:

  1. 春天创建您的实例。

  2. 把它们变成吉斯

  3. 创建由吉斯创建委托对象和的豆注入(1)进入包装。

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

+0

是的,我也做了这件事情,它的作品像魅力。在我的情况下,弹簧加载所有的依赖关系,所以我做了一些配置更改。 –

+0

听起来不错:)你可以标记答案是正确的,如果它回答你的查询 – pandaadb