1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/** 定义目标类 */
public class AspectTarget {

    public void method1() {
        System.out.println("method1 execution");
    }

    public void method2() {
        System.out.println("method2 execution");
    }

}
/** 定义切面 */
@Aspect
public class PerformanceTraceAspect {

    @Pointcut("execution(public void *.method1()) || execution(public void *.method2())")
    public void pointcut() {}

    @Around("pointcut()")
    public Object performanceTrace(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        try {
            stopWatch.start();
            return joinPoint.proceed();
        } finally {
            stopWatch.stop();
            System.out.println("monitor: " + 
                    // 获取调用的方法名
                    joinPoint.getSignature().getName());
        }
    }
}

/** 测试 */
public class Main {
    public static void main(String[] args) {
        AspectJProxyFactory aspectJProxyFactory = new AspectJProxyFactory();
        // 设置需要代理的目标类
        aspectJProxyFactory.setTarget(new AspectTarget());
        // 设置切面
        aspectJProxyFactory.addAspect(PerformanceTraceAspect.class);
        AspectTarget proxy = aspectJProxyFactory.getProxy();
        proxy.method1();
        proxy.method2();
    }
}

输出
method1 execution
monitor: method1
method2 execution
monitor: method2