Spring AOP建议正在执行两次

时间:2015-01-07 08:48:46

标签: java spring spring-mvc aop spring-aop

我正在使用Spring AOP创建一个Aspect。我定义的Aspect正在执行两次。我似乎无法弄清楚原因。我很感激任何人对此问题的任何意见。

谢谢!

//弹簧配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
    default-autowire="no"
    default-lazy-init="true">

    <bean id="loggingAdvice" class="com.xyz.aop.LoggingAdvice" />
    <aop:config>
        <aop:aspect id="loggingAspect" ref="loggingAdvice">
            <aop:pointcut id="loggingPointcut"
                expression="execution(* com.xyz.FooServiceImpl.foo(..))"/>
                <aop:around pointcut-ref="loggingPointcut" method="log" />
        </aop:aspect>
    </aop:config>

    <context:component-scan base-package="com.xyz.controllers" />

</beans>

//建议

package com.xyz.aop;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;

public class LoggingAdvice {
    public Object log(final ProceedingJoinPoint pjp) throws Throwable {
        log.info("Started!");
        try {
            return pjp.proceed();
        } finally {
            log.info("Ended!");
        }
    }
}

//建议方法

package com.xyz;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FooServiceImpl implements FooService {
    private static final Log log = LogFactory.getLog(FooServiceImpl.class);

    @Override
    public void foo()  {
         log.info("Foo!");
        }
    }
}

//输出

   Started!
   Started!
   Foo!
   Ended!
   Ended!

//编辑1:添加了更多弹簧配置信息。根本不使用任何Spring AOP注释。我附加了一个调试器,发现方面/日志语句也被执行了两次。所以我怀疑它与log语句打印两次字符串有什么关系。

2 个答案:

答案 0 :(得分:0)

嗯,看起来这实际上是记录器的一个问题。同样的问题我很久以前遇到过,发现一切都被记录了两次。当我用常规的sysout调用替换记录器调用时,一切正常。

答案 1 :(得分:-1)

因为<aop:around ...&gt;告诉这个在方法之前和之后做的工作。您可以使用<aop:before...><aop:after...>代替仅运行一次。

相关问题