Spring--官方文档部分翻译(第六章 AOP)

6.1 切点API

6.11 概念

  • 核心接口:org.springframework.aop.Pointcut
public interface Pointcut {
    ClassFilter getClassFilter();
    MethodMatcher getMethodMatcher();
}
  • 两个子对象都有matches方法,用于测试切点是否匹配特定的类或方法。这种测试在AOP代理生成时完成以避免在每次方法调用时测试。
  • 如果一个方法的2参数matches和isRuntime都为true,那么每次方法调用时3参数matches都会被调用,这使得在方法调用时可以核查参数信息。
  • 大部分MethodMatcher的实现为static,isRuntime始终返回false,则其3参数matches永远不会触发。
  • 尽量让切点定义为static,以允许spring在AOP代理生成时缓存切点评估的结果。
public interface MethodMatcher {
    boolean matches(Method m, Class targetClass);
    boolean isRuntime();
    boolean matches(Method m, Class targetClass, Object[] args);
}

6.1.4 切点实现

6.2 Advice API

6.2.1 Advice生命周期

  • 每个Advice是一个bean。An advice instance can be shared across all advised objects or be unique to each advised object. This corresponds to per-class or per-instance advice.
  • Per-class advice使用更广泛。

6.2.1 Advice Type

  • 拦截器:最基础的Advice Type是环绕Advice的拦截器。
  • 需要实现MethodInterceptor接口(invoke方法返回调用的结果)
public interface MethodInterceptor extends Interceptor {
    Object invoke(MethodInvocation invocation) throws Throwable;
}

public class DebugInterceptor implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("Before: invocation=[" + invocation + "]");
        Object rval = invocation.proceed();
        System.out.println("Invocation returned");
        return rval;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40632321/article/details/85238721
今日推荐