使用Spring AOP来记录Spring框架类的方法

时间:2014-07-22 19:22:54

标签: spring aspectj spring-aop

有没有办法使用Spring AOP在spring框架类下记录方法的进入和退出?
例如:
我想记录出口和出口 refresh()班中的org.springframework.context.support.AbstractApplicationContext

我尝试了以下内容。但没有运气:(

@Around("execution(* org.springframework.context.*(..))")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("Entry Into Method : " + joinPoint.getSignature().getName());
    System.out.println("Arguments : " + Arrays.toString(joinPoint.getArgs()));

    joinPoint.proceed();

    System.out.println("Exit from Method : " + joinPoint.getSignature().getName());
}


但我最终得到了bean创建异常。

1 个答案:

答案 0 :(得分:0)

我认为这不会起作用,只是因为你试图在一个类上拦截一些方法(在调用refresh()之后)它开始创建AOP所需的bean。

我相信你需要使用AspectJ。定义为与以下MyAspect.aj类似的方面:

package com.foo.bar;

public aspect MyAspect {

    static final void println(String s) {
        System.out.println(s);
    }

    pointcut aroundAppContext():
        execution(* org.springframework.context.support.*.*(..));

    Object around(): aroundAppContext() {
        println("Intercepted message: " + thisJoinPointStaticPart.getSignature().getName());
        println("in class: " + thisJoinPointStaticPart.getSignature().getDeclaringType().getName());
        Object result = proceed();
        println("  result: " + result);
        return result;
    }

}

在项目中定义一个META-INF/aop.xml文件,其中包含以下内容:

<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>

    <weaver> <!-- options="-debug -verbose -showWeaveInfo"> -->
        <!-- only weave classes in our application-specific packages -->
        <include  within="org.springframework.context.support.*"/>
    </weaver>

    <aspects>
        <!-- weave in just this aspect -->
        <aspect name="com.foo.bar.MyAspect"/>
    </aspects>

</aspectj>

并使用-javaagent选项运行您的项目,就像参考文档提到here一样。