Join point

  1. package org.aopalliance.intercept.Joinpoint
  2. public interface Joinpoint {
  3. // 返回 Joinpoint 对应成员,在SpringAop
  4. Object proceed() throws Throwable;
  5. Object getThis();
  6. AccessibleObject getStaticPart();
  7. }

Pointcut

  • Pointcut 核心组件
  1. package org.springframework.aop;
  2. //判断模式 - join point 条件接口
  3. public interface Pointcut {
  4. Pointcut TRUE = TruePointcut.INSTANCE;
  5. // 类过滤器 - 判断类是否符合
  6. ClassFilter getClassFilter();
  7. // 方法匹配器
  8. MethodMatcher getMethodMatcher();
  9. }
  • pointcut 方法匹配器的方法返回值
  1. package org.springframework.aop;
  2. import java.lang.reflect.Method;
  3. //pointcut 方法匹配器的方法返回值
  4. public interface MethodMatcher {
  5. MethodMatcher TRUE = TrueMethodMatcher.INSTANCE;
  6. //非参数拦截
  7. boolean matches(Method var1, Class<?> var2);
  8. //判断是否是运行时。false-静态;true-动态;静态不实现参数拦截方法,如StaticMethodMatcher
  9. boolean isRuntime();
  10. //参数拦截
  11. boolean matches(Method var1, Class<?> var2, Object... var3);
  12. }
  • pointcut 组合实现
  1. package org.springframework.aop.support;
  2. public class ComposablePointcut implements Pointcut, Serializable {
  3. //采用 union-组合 intersection-交叉 等方式实现组合过滤
  4. }
  5. // 工具类
  6. //ClassFilters
  7. //MethodMatchers
  8. //Pointcuts
  • pointcut 便利实现
    • 静态实现 - StaticMethodMatcherPointcut
    • 正则表达式 - JdkRegexpMethodPointcut
    • 控制流 - ControlFlowPointcut
  • pointcut AspectJ 实现
    • 实现类 :org.springframework.aop.aspectj.AspectJExpressionPointcut
    • 指令支持 : SUPPORTED_PRIMITIVES
    • 表达式 :org.aspectj.lang.reflect.PointcutExpression

      Advice - Joinpoint 执行动作接口

Arount Advice - Interceptor

  • 方法拦截 : MethodInterceptor
  • 构造器拦截 : ConstructorIntercpetor

    Joinpoint Before Advice

  • 标准接口: org.springframework.aop.BeforeAdvice

  • 方法级别:org.springframework.aop.MethodBeforeAdvice
  • 实现:org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor
  • AspectJ 实现:org.springframework.aop.aspectj.AspectJMethodBeforeAdvice

    Spring AspectJ 通过反射动态实现,用反射的方式获取元信息,判断是否符合

Joinpoint After Advcie

  • 接口
    • org.springframework.aop.AfterAdvice
    • org.springframework.aop.AfterReturningAdvice
    • org.springframework.aop.ThrowsAdvice
  • 标准实现
    • org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor
    • org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor
  • AspectJ 实现
    • org.springframework.aop.aspectj.AspectJAfterAdvice
    • org.springframework.aop.aspectj.AspectJAfterReturningAdvice
    • org.springframework.aop.aspectj.AspectJAfterThrowingAdvice

AfterReturningAdviceInterceptor -> AspectJAfterReturningAdvice -> AspectJAfterAdvice # invokeAdviceMethodWithGivenArgs

Advistor - Advice 容器接口 (更底层)

  • 接口:org.springframework.aop.Advisor
  • 通用实现:org.springframework.aop.support.DefaultPointcutAdvisor

PointcutAdvice - pointcut 与 Advice 连接器

方法和类型都会过滤

  • 接口:org.springframework.aop.PointcutAdvisor
  • 通用实现:org.springframework.aop.support.DefaultPointcutAdvisor
  • Aspect 实现:
    • org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor
    • org.springframework.aop.aspectj.AspectJPointcutAdvisor
  • 静态方法实现:org.springframework.aop.aspectj.AspectJPointcutAdvisor
  • IOC 容器实现:org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor

IntroductionAdvisor - Introduction 与 Advice 连接器

  • 接口:org.springframework.aop.IntroductionAdvisor
  • 元信息:org.springframework.aop.IntroductionInfo
  • 通用实现:org.springframework.aop.support.DefaultIntroductionAdvisor
  • AspectJ实现:org.springframework.aop.support.DefaultPointcutAdvisor

AdvisorAdapter - Advisor 的 Interceptor 适配器

  • 接口 :org.springframework.aop.framework.adapter.AdvisorAdapter
  1. // 转换器、适配器 将 Advisor 转换成 Interceptor
  2. public interface AdvisorAdapter {
  3. // 判断Advice支不支持
  4. boolean supportsAdvice(Advice var1);
  5. // Advisor 转换称 Interceptor (底层所有的 Advice 都是转换成 MethodInterceptor 进行实现)
  6. MethodInterceptor getInterceptor(Advisor var1);
  7. }
  • MethodBeforeAdvice 实现
    • org.springframework.aop.framework.adapter.MethodBeforeAdviceAdapter
  1. class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
  2. MethodBeforeAdviceAdapter() {
  3. }
  4. // 判断是 MethodBeforeAdvice
  5. public boolean supportsAdvice(Advice advice) {
  6. return advice instanceof MethodBeforeAdvice;
  7. }
  8. // 返回 MethodBeforeAdviceInterceptor
  9. public MethodInterceptor getInterceptor(Advisor advisor) {
  10. MethodBeforeAdvice advice = (MethodBeforeAdvice)advisor.getAdvice();
  11. return new MethodBeforeAdviceInterceptor(advice);
  12. }
  13. }
  • AfterReturningAdviceAdapter 实现
    • org.springframework.aop.framework.adapter.AfterReturningAdviceAdapter
  • ThrowsAdviceAdapter 实现
    • org.springframework.aop.framework.adapter.ThrowsAdviceAdapter

可以通过 AdviceAdapter 对 Advice 进行扩展

AopProxy

  • 接口:org.springframework.aop.framework.AopProxy
  1. package org.springframework.aop.framework;
  2. import org.springframework.lang.Nullable;
  3. // 允许创建实际的代理对象
  4. public interface AopProxy {
  5. //获取代理对象
  6. Object getProxy();
  7. Object getProxy(@Nullable ClassLoader var1);
  8. }
  • 实现:
    • JDK 动态代理
      • org.springframework.aop.framework.JdkDynamicAopProxy
    • CGLIB 字节码提升
      • org.springframework.aop.framework.CglibAopProxy
        • org.springframework.aop.framework.ObjenesisCglibAopProxy

AopProxy 工厂接口与实现

  • 接口:org.springframework.aop.framework.AopProxyFactory
  1. //创建一个AopProxy
  2. public interface AopProxyFactory {
  3. // AdvisedSupport :配置
  4. AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException;
  5. }
  • 默认实现:org.springframework.aop.framework.DefaultAopProxyFactory
  1. //怎么创建工厂的?
  2. public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
  3. public DefaultAopProxyFactory() {
  4. }
  5. public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
  6. // 判断配置是否符合条件
  7. if (!config.isOptimize() && !config.isProxyTargetClass() && !this.hasNoUserSuppliedProxyInterfaces(config)) {
  8. return new JdkDynamicAopProxy(config);
  9. } else {
  10. // 获取被代理对象
  11. Class<?> targetClass = config.getTargetClass();
  12. if (targetClass == null) {
  13. throw new AopConfigException("TargetSource cannot determine target class: Either an interface or a target is required for proxy creation.");
  14. } else {
  15. //如果 targetClass 是接口或者属于 proxy class,则通过 JDK 动态代理实现,否则使用 Cglib 实现。
  16. return (AopProxy)(!targetClass.isInterface() && !Proxy.isProxyClass(targetClass) ? new ObjenesisCglibAopProxy(config) : new JdkDynamicAopProxy(config));
  17. }
  18. }
  19. }
  20. private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
  21. Class<?>[] ifcs = config.getProxiedInterfaces();
  22. return ifcs.length == 0 || ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0]);
  23. }
  24. }
  • 返回类型
    • org.springframework.aop.framework.JdkDynamicAopProxy
    • org.springframework.aop.framework.CglibAopProxy
      • org.springframework.aop.framework.ObjenesisCglibAopProxy

为什么工厂没有设置 AspectJ ?

JdkDynamicAopProxy - JDK AopProxy 实现

  • 实现:org.springframework.aop.framework.JdkDynamicAopProxy
    • 配置:org.springframework.aop.framework.AdvisedSupport
    • 来源:org.springframework.aop.framework.DefaultAopProxyFactory

CGLIB AopProxy 实现 - CglibAopProxy实现

  • 实现 - org.springframework.aop.framework.CglibAopProxy
    • 配置:org.springframework.aop.framework.AdvisedSupport
    • 来源:org.springframework.aop.framework.DefaultAopProxyFactory

AopProxyFactory 配置管理器

  • 核心API - org.springframework.aop.framework.AdvisedSupport
    • 语义 - 代理对象的配置
    • 基类 - org.springframework.aop.framework.ProxyConfig
    • 实现接口 - org.springframework.aop.framework.Advised
    • 使用场景 - org.springframework.aop.framework.AopProxy 实现

ProxyConfig 配置含义

  1. public class ProxyConfig implements Serializable {
  2. private static final long serialVersionUID = -8409359707199703185L;
  3. //代理类型选择
  4. private boolean proxyTargetClass = false;
  5. private boolean optimize = false;
  6. boolean opaque = false;
  7. boolean exposeProxy = false;
  8. //配置是否冻结
  9. private boolean frozen = false;
  10. }

AdvisedSupport 配置含义

  1. public class AdvisedSupport extends ProxyConfig implements Advised {
  2. private static final long serialVersionUID = 2651364800145442165L;
  3. public static final TargetSource EMPTY_TARGET_SOURCE;
  4. TargetSource targetSource;
  5. private boolean preFiltered;
  6. // advisor 动作的一个实现
  7. AdvisorChainFactory advisorChainFactory;
  8. // 根据方法进行缓存,目标方法就是返回的key
  9. private transient Map<AdvisedSupport.MethodCacheKey, List<Object>> methodCache;
  10. // 目标对象所实现的所有接口的集合
  11. private List<Class<?>> interfaces;
  12. // advice 的内部封装,是AOP 视角的API,advice是面对用户视角的API
  13. private List<Advisor> advisors;
  14. }

Advisor 链工厂接口与实现

  • 核心API : org.springframework.aop.framework.AdvisorChainFactory
    • 特殊实现:org.springframework.aop.framework.InterceptorAndDynamicMethodMatcher
    • 默认实现:org.springframework.aop.framework.DefaultAdvisorChainFactory

DefaultAdvisorChainFactory 的实现主要是将Advisor获取AdvisorAdapter,从而把AdvisorAdapter变成MethodInterceptor。

也可以说,是将一个Advice做为用户的API对象,将用户的API对象转换成对应的Advisor对象,从而把Advice最终转换成MethodInterceptor。这就是整个AOP的一个核心语义。

  1. package org.springframework.aop.framework;
  2. import java.io.Serializable;
  3. import java.lang.reflect.Method;
  4. import java.util.ArrayList;
  5. import java.util.Arrays;
  6. import java.util.List;
  7. import org.aopalliance.intercept.Interceptor;
  8. import org.aopalliance.intercept.MethodInterceptor;
  9. import org.springframework.aop.Advisor;
  10. import org.springframework.aop.IntroductionAdvisor;
  11. import org.springframework.aop.IntroductionAwareMethodMatcher;
  12. import org.springframework.aop.MethodMatcher;
  13. import org.springframework.aop.PointcutAdvisor;
  14. import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry;
  15. import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry;
  16. import org.springframework.lang.Nullable;
  17. /**
  18. * A simple but definitive way of working out an advice chain for a Method,
  19. * given an {@link Advised} object. Always rebuilds each advice chain;
  20. * caching can be provided by subclasses.
  21. *
  22. * @author Juergen Hoeller
  23. * @author Rod Johnson
  24. * @author Adrian Colyer
  25. * @since 2.0.3
  26. */
  27. @SuppressWarnings("serial")
  28. public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable {
  29. @Override
  30. public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
  31. Advised config, Method method, @Nullable Class<?> targetClass) {
  32. // This is somewhat tricky... We have to process introductions first,
  33. // but we need to preserve order in the ultimate list.
  34. AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
  35. Advisor[] advisors = config.getAdvisors();
  36. List<Object> interceptorList = new ArrayList<>(advisors.length);
  37. Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
  38. Boolean hasIntroductions = null;
  39. for (Advisor advisor : advisors) {
  40. if (advisor instanceof PointcutAdvisor) {
  41. // Add it conditionally.
  42. PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
  43. if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
  44. MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
  45. boolean match;
  46. if (mm instanceof IntroductionAwareMethodMatcher) {
  47. if (hasIntroductions == null) {
  48. hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
  49. }
  50. match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
  51. }
  52. else {
  53. match = mm.matches(method, actualClass);
  54. }
  55. if (match) {
  56. MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
  57. if (mm.isRuntime()) {
  58. // Creating a new object instance in the getInterceptors() method
  59. // isn't a problem as we normally cache created chains.
  60. for (MethodInterceptor interceptor : interceptors) {
  61. interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
  62. }
  63. }
  64. else {
  65. interceptorList.addAll(Arrays.asList(interceptors));
  66. }
  67. }
  68. }
  69. }
  70. else if (advisor instanceof IntroductionAdvisor) {
  71. IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
  72. if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
  73. Interceptor[] interceptors = registry.getInterceptors(advisor);
  74. interceptorList.addAll(Arrays.asList(interceptors));
  75. }
  76. }
  77. else {
  78. Interceptor[] interceptors = registry.getInterceptors(advisor);
  79. interceptorList.addAll(Arrays.asList(interceptors));
  80. }
  81. }
  82. return interceptorList;
  83. }

存储并转换的注入中心

  1. package org.springframework.aop.framework.adapter;
  2. public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable {
  3. private final List<AdvisorAdapter> adapters = new ArrayList<>(3);
  4. /**
  5. * Create a new DefaultAdvisorAdapterRegistry, registering well-known adapters.
  6. * 存储并转换的注入中心
  7. */
  8. public DefaultAdvisorAdapterRegistry() {
  9. registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
  10. registerAdvisorAdapter(new AfterReturningAdviceAdapter());
  11. registerAdvisorAdapter(new ThrowsAdviceAdapter());
  12. }
  13. }

目标对象来源接口与实现

  • 核心API : org.springframework.aop.TargetSource
    • 实现
      • org.springframework.aop.target.HotSwappableTargetSource
      • org.springframework.aop.target.AbstractPoolingTargetSource
      • org.springframework.aop.target.PrototypeTargetSource
      • org.springframework.aop.target.ThreadLocalTargetSource
      • org.springframework.aop.target.SingletonTargetSource
  1. public interface TargetSource extends TargetClassAware {
  2. /**
  3. * Return the type of targets returned by this {@link TargetSource}.
  4. * <p>Can return {@code null}, although certain usages of a {@code TargetSource}
  5. * might just work with a predetermined target class.
  6. * @return the type of targets returned by this {@link TargetSource}
  7. * 获取目标对象的类
  8. */
  9. @Override
  10. @Nullable
  11. Class<?> getTargetClass();
  12. /**
  13. * Will all calls to {@link #getTarget()} return the same object?
  14. * <p>In that case, there will be no need to invoke {@link #releaseTarget(Object)},
  15. * and the AOP framework can cache the return value of {@link #getTarget()}.
  16. * 是否返回相同的对象,如果是相同的对象,则不做操作。如果是不同的对象,则需要使用releaseTarget
  17. * @return {@code true} if the target is immutable
  18. * @see #getTarget
  19. */
  20. boolean isStatic();
  21. /**
  22. * Return a target instance. Invoked immediately before the
  23. * AOP framework calls the "target" of an AOP method invocation.
  24. * @return the target object which contains the joinpoint,
  25. * or {@code null} if there is no actual target instance
  26. * @throws Exception if the target object can't be resolved
  27. * 返回目标对象的实例
  28. */
  29. @Nullable
  30. Object getTarget() throws Exception;
  31. /**
  32. * Release the given target object obtained from the
  33. * {@link #getTarget()} method, if any.
  34. * @param target object obtained from a call to {@link #getTarget()}
  35. * @throws Exception if the object can't be released
  36. */
  37. void releaseTarget(Object target) throws Exception;
  38. }

代理对象创建的基础类

  • 核心API org.springframework.aop.framework.ProxyCreateSuppot
    • 语义 - 代理对象创建基类
    • 基类 - org.springframework.aop.framework.AdvisedSupport
    • ProxyCreateSuppot 与 AdviceSupport 的区别:
      • ProxyCreateSuppotr 更关注于对象的创建主要和 AopProxyFactory 产生一个关联,创建对应的字节码提升或者Cglib提升
      • AdviceSupport 装配或者关联Aop配置的一个很重要的信息

开关 ProxyTargetClass = true or false

true - cglib

false - java 动态代理

Spring 三种实现:

  • Java动态代理
  • Cglib字节码提升
  • AspectJ -> Java 反射
    • 动态代理 -> 接口
    • Cglib 字节码提升 -> 类对象

将Advisor获取AdvisorAdapter,从而把AdvisorAdaptor变成MethodInterceptor

一个Advice 作为用户的API对象,将用户API对象转换成对应的Adviser对象

AdvisedSupport 事件监听

  • 核心API - org.springframework.aop.framework.AdvisedSupportListener
    • 事件对象 - org.springframework.aop.framework.AdvisedSupport
    • 事件来源 - org.springframework.aop.framework.ProxyCreatorSupport
    • 激活事件触发- ProxyCreatorSupport#createAopProxy
    • 变更事件触发- 代理接口变化时,Advisor 变化时,配置复制

ProxyCreatorSupport 的标准实现

  • 核心API - org.springframework.aop.framework.ProxyFactory
    • 基类 - org.springframework.aop.framework.ProxyCreatorSupport
    • 特性增强
      • 提供一些便利操作

ProxyCreatorSupport 的IOC 容器实现

  • 核心API - org.springframework.aop.framework.ProxyFactoryBean
    • 基类 - org.springframework.aop.framework.ProxyCreatorSupport
    • 特点
      • Spring IOC 容器整合
        • org.springframework.beans.factory.BeanClassLoaderAware
        • org.springframework.beans.factory.BeanFactoryAware
      • 特性增强
        • 实现 org.springframework.beans.factory.FactoryBean

ProxyCreatorSupport AspectJ 实现

  • 核心API - org.springframework.aop.aspectj.annotation.AspectJProxyFactory
    • 基类 - org.springframework.aop.framework.ProxyCreatorSupport
    • 特点
      • AspectJ 注解整合
    • 相关API
      • AspectJ 元数据 - org.springframework.aop.aspectj.annotation.AspectMetadata
      • AspectJ Advisor工厂 - org.springframework.aop.aspectj.annotation.AspectJAdvisorFactory

IOC 容器自动代理抽象

  • 核心API - org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator
    • 基类 - org.springframework.aop.framework.ProxyProcessorSupport
    • 特点
      • 与Spring bean 生命周期整合
        • org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor