简体   繁体   English

Spring AOP @注释

[英]Spring AOP @annotation

I'm newbie in AOP especially in Spring AOP. 我是AOP的新手,尤其是Spring AOP。

I want to log execution time in some specific method. 我想以某种特定方法记录执行时间。 I read Spring documentation and considered that the best solution is to create aspect with annotation pointcut. 我阅读了Spring文档,并认为最好的解决方案是使用注释切入点创建方面。

It looks like: 看起来像:

@Around("@annotation(com.x.y.MethodExecutionTime)")
public Object methodExecutionTimeLog(ProceedingJoinPoint joinPoint) throws Throwable 
    StopWatch stopWatch = new StopWatch();

    Object retVal = null;
    try {
        stopWatch.start();
        retVal = joinPoint.proceed();
        stopWatch.stop();
        logger.info("Execution time: " + stopWatch.getTotalTimeMillis() + " ms");
    } catch(Throwable e) {
        logger.error("Execution time: " + stopWatch.getTotalTimeMillis() + " ms");
        throw e;
    }
    return retVal;
}

Annotation is used in method: 在方法中使用注释:

    @Override
@MethodExecutionTime
public <T> T copy(Class<T> destType) {

    T t = ReflectionHelper.newInstance(destType);

    copyTo(t);

    return t;
}

Spring XML configuration: Spring XML配置:

<context:spring-configured />
<aop:aspectj-autoproxy proxy-target-class="true" />

but it logs nothing. 但它什么也不记录。

I'm using Spring 3.0.5 我正在使用Spring 3.0.5

Any ideas? 有任何想法吗? Thanks 谢谢

If everything else is configured properly, it should be one of the limitations of Spring AOP (at least, of its default configuration), namely: 如果其他所有配置都正确,那么它应该是Spring AOP的限制之一(至少是其默认配置),即:

  • Object to apply the aspect to should be managed by Spring (ie it should be obtained from the application context, not created with new ) 应用方面的对象应由Spring管理(即应从应用程序上下文中获取,而不是使用new创建)

  • Call should originate from the "outside" of that object, ie aspects are not applied when you call another method of the same object 调用应从该对象的“外部”发起,即,当您调用同一对象的另一种方法时,方面将不适用

  • <aop:aspectj-autoproxy> should be declared in the same application context as the object to apply the aspect to (in particular, in a typical Spring Web MVC application applicationContext.xml and ...-servlet.xml form different application contexts) <aop:aspectj-autoproxy>应该在与要应用方面的对象相同的应用程序上下文中声明(尤其是在典型的Spring Web MVC应用applicationContext.xml...-servlet.xml形成不同的应用程序上下文)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM