Spring AOP建议被多次调用

时间:2018-01-30 20:53:50

标签: java spring spring-aop

我有一个方法需要在执行前后截获,所以为了做到这一点,我使用了AspectJ

效果很好,但出于某种原因,这些建议被多次调用。

查看调用层次结构时,我注意到在调用joinPoint.proceed();而不是继续执行方法时,我再次使用了advice方法。

我无法弄清楚为什么我会多次调用通知方法,尽管我只调用getCacheableSite(String siteId)一次。

Spring xml配置:

<bean id="runtimeCacheAspect" class="site.aspect.RuntimeCacheAspect">
<aop:aspectj-autoproxy />

<aop:config>
    <aop:aspect id="aspectLogging" ref="runtimeCacheAspect" >
        <!-- @Around -->
        <aop:pointcut id="pointCutAround"
                      expression="execution(public * getCacheableSite(..))" />
        <aop:around method="getData" pointcut-ref="pointCutAround" />

    </aop:aspect>
</aop:config>

建议:

public Object getData(ProceedingJoinPoint joinPoint) throws Throwable {
    Object returnObject = null;
    try {
        System.out.println("Before");
        returnObject = joinPoint.proceed();
    } catch (Throwable throwable) {
        throw throwable;
    }
    finally {
        System.out.println("After");
    }
    return returnObject;

需要拦截的方法:

    public JsonObject getCacheableSite(String siteId) {
        System.out.println("Method being executed..."); 
}

输出:

Before
Before
Before
Before
Before
Before
Before
Before
Before
Before
Method being executed...
After
After
After
After
After
After
After
After
After
After

1 个答案:

答案 0 :(得分:0)

这解决了我的问题:

    <aop:aspectj-autoproxy proxy-target-class="true" expose-proxy="true">
        <aop:include name="getCacheableSite" />
    </aop:aspectj-autoproxy>