Join point
package org.aopalliance.intercept.Joinpointpublic interface Joinpoint {// 返回 Joinpoint 对应成员,在SpringAopObject proceed() throws Throwable;Object getThis();AccessibleObject getStaticPart();}
Pointcut
- Pointcut 核心组件
package org.springframework.aop;//判断模式 - join point 条件接口public interface Pointcut {Pointcut TRUE = TruePointcut.INSTANCE;// 类过滤器 - 判断类是否符合ClassFilter getClassFilter();// 方法匹配器MethodMatcher getMethodMatcher();}
- pointcut 方法匹配器的方法返回值
package org.springframework.aop;import java.lang.reflect.Method;//pointcut 方法匹配器的方法返回值public interface MethodMatcher {MethodMatcher TRUE = TrueMethodMatcher.INSTANCE;//非参数拦截boolean matches(Method var1, Class<?> var2);//判断是否是运行时。false-静态;true-动态;静态不实现参数拦截方法,如StaticMethodMatcherboolean isRuntime();//参数拦截boolean matches(Method var1, Class<?> var2, Object... var3);}
- pointcut 组合实现
package org.springframework.aop.support;public class ComposablePointcut implements Pointcut, Serializable {//采用 union-组合 intersection-交叉 等方式实现组合过滤}// 工具类//ClassFilters//MethodMatchers//Pointcuts
- pointcut 便利实现
- 静态实现 - StaticMethodMatcherPointcut
- 正则表达式 - JdkRegexpMethodPointcut
- 控制流 - ControlFlowPointcut
- pointcut AspectJ 实现
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
// 转换器、适配器 将 Advisor 转换成 Interceptorpublic interface AdvisorAdapter {// 判断Advice支不支持boolean supportsAdvice(Advice var1);// Advisor 转换称 Interceptor (底层所有的 Advice 都是转换成 MethodInterceptor 进行实现)MethodInterceptor getInterceptor(Advisor var1);}
- MethodBeforeAdvice 实现
- org.springframework.aop.framework.adapter.MethodBeforeAdviceAdapter
class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {MethodBeforeAdviceAdapter() {}// 判断是 MethodBeforeAdvicepublic boolean supportsAdvice(Advice advice) {return advice instanceof MethodBeforeAdvice;}// 返回 MethodBeforeAdviceInterceptorpublic MethodInterceptor getInterceptor(Advisor advisor) {MethodBeforeAdvice advice = (MethodBeforeAdvice)advisor.getAdvice();return new MethodBeforeAdviceInterceptor(advice);}}
- AfterReturningAdviceAdapter 实现
- org.springframework.aop.framework.adapter.AfterReturningAdviceAdapter
- ThrowsAdviceAdapter 实现
- org.springframework.aop.framework.adapter.ThrowsAdviceAdapter
可以通过 AdviceAdapter 对 Advice 进行扩展
AopProxy
- 接口:org.springframework.aop.framework.AopProxy
package org.springframework.aop.framework;import org.springframework.lang.Nullable;// 允许创建实际的代理对象public interface AopProxy {//获取代理对象Object getProxy();Object getProxy(@Nullable ClassLoader var1);}
- 实现:
- JDK 动态代理
- org.springframework.aop.framework.JdkDynamicAopProxy
- CGLIB 字节码提升
- org.springframework.aop.framework.CglibAopProxy
- org.springframework.aop.framework.ObjenesisCglibAopProxy
- org.springframework.aop.framework.CglibAopProxy
- JDK 动态代理
AopProxy 工厂接口与实现
- 接口:org.springframework.aop.framework.AopProxyFactory
//创建一个AopProxypublic interface AopProxyFactory {// AdvisedSupport :配置AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException;}
- 默认实现:org.springframework.aop.framework.DefaultAopProxyFactory
//怎么创建工厂的?public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {public DefaultAopProxyFactory() {}public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {// 判断配置是否符合条件if (!config.isOptimize() && !config.isProxyTargetClass() && !this.hasNoUserSuppliedProxyInterfaces(config)) {return new JdkDynamicAopProxy(config);} else {// 获取被代理对象Class<?> targetClass = config.getTargetClass();if (targetClass == null) {throw new AopConfigException("TargetSource cannot determine target class: Either an interface or a target is required for proxy creation.");} else {//如果 targetClass 是接口或者属于 proxy class,则通过 JDK 动态代理实现,否则使用 Cglib 实现。return (AopProxy)(!targetClass.isInterface() && !Proxy.isProxyClass(targetClass) ? new ObjenesisCglibAopProxy(config) : new JdkDynamicAopProxy(config));}}}private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {Class<?>[] ifcs = config.getProxiedInterfaces();return ifcs.length == 0 || ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0]);}}
- 返回类型
- 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 配置含义
public class ProxyConfig implements Serializable {private static final long serialVersionUID = -8409359707199703185L;//代理类型选择private boolean proxyTargetClass = false;private boolean optimize = false;boolean opaque = false;boolean exposeProxy = false;//配置是否冻结private boolean frozen = false;}
AdvisedSupport 配置含义
public class AdvisedSupport extends ProxyConfig implements Advised {private static final long serialVersionUID = 2651364800145442165L;public static final TargetSource EMPTY_TARGET_SOURCE;TargetSource targetSource;private boolean preFiltered;// advisor 动作的一个实现AdvisorChainFactory advisorChainFactory;// 根据方法进行缓存,目标方法就是返回的keyprivate transient Map<AdvisedSupport.MethodCacheKey, List<Object>> methodCache;// 目标对象所实现的所有接口的集合private List<Class<?>> interfaces;// advice 的内部封装,是AOP 视角的API,advice是面对用户视角的APIprivate List<Advisor> advisors;}
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的一个核心语义。
package org.springframework.aop.framework;import java.io.Serializable;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import org.aopalliance.intercept.Interceptor;import org.aopalliance.intercept.MethodInterceptor;import org.springframework.aop.Advisor;import org.springframework.aop.IntroductionAdvisor;import org.springframework.aop.IntroductionAwareMethodMatcher;import org.springframework.aop.MethodMatcher;import org.springframework.aop.PointcutAdvisor;import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry;import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry;import org.springframework.lang.Nullable;/*** A simple but definitive way of working out an advice chain for a Method,* given an {@link Advised} object. Always rebuilds each advice chain;* caching can be provided by subclasses.** @author Juergen Hoeller* @author Rod Johnson* @author Adrian Colyer* @since 2.0.3*/@SuppressWarnings("serial")public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable {@Overridepublic List<Object> getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, @Nullable Class<?> targetClass) {// This is somewhat tricky... We have to process introductions first,// but we need to preserve order in the ultimate list.AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();Advisor[] advisors = config.getAdvisors();List<Object> interceptorList = new ArrayList<>(advisors.length);Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());Boolean hasIntroductions = null;for (Advisor advisor : advisors) {if (advisor instanceof PointcutAdvisor) {// Add it conditionally.PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();boolean match;if (mm instanceof IntroductionAwareMethodMatcher) {if (hasIntroductions == null) {hasIntroductions = hasMatchingIntroductions(advisors, actualClass);}match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);}else {match = mm.matches(method, actualClass);}if (match) {MethodInterceptor[] interceptors = registry.getInterceptors(advisor);if (mm.isRuntime()) {// Creating a new object instance in the getInterceptors() method// isn't a problem as we normally cache created chains.for (MethodInterceptor interceptor : interceptors) {interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));}}else {interceptorList.addAll(Arrays.asList(interceptors));}}}}else if (advisor instanceof IntroductionAdvisor) {IntroductionAdvisor ia = (IntroductionAdvisor) advisor;if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {Interceptor[] interceptors = registry.getInterceptors(advisor);interceptorList.addAll(Arrays.asList(interceptors));}}else {Interceptor[] interceptors = registry.getInterceptors(advisor);interceptorList.addAll(Arrays.asList(interceptors));}}return interceptorList;}
存储并转换的注入中心
package org.springframework.aop.framework.adapter;public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable {private final List<AdvisorAdapter> adapters = new ArrayList<>(3);/*** Create a new DefaultAdvisorAdapterRegistry, registering well-known adapters.* 存储并转换的注入中心*/public DefaultAdvisorAdapterRegistry() {registerAdvisorAdapter(new MethodBeforeAdviceAdapter());registerAdvisorAdapter(new AfterReturningAdviceAdapter());registerAdvisorAdapter(new ThrowsAdviceAdapter());}}
目标对象来源接口与实现
- 核心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
- 实现
public interface TargetSource extends TargetClassAware {/*** Return the type of targets returned by this {@link TargetSource}.* <p>Can return {@code null}, although certain usages of a {@code TargetSource}* might just work with a predetermined target class.* @return the type of targets returned by this {@link TargetSource}* 获取目标对象的类*/@Override@NullableClass<?> getTargetClass();/*** Will all calls to {@link #getTarget()} return the same object?* <p>In that case, there will be no need to invoke {@link #releaseTarget(Object)},* and the AOP framework can cache the return value of {@link #getTarget()}.* 是否返回相同的对象,如果是相同的对象,则不做操作。如果是不同的对象,则需要使用releaseTarget* @return {@code true} if the target is immutable* @see #getTarget*/boolean isStatic();/*** Return a target instance. Invoked immediately before the* AOP framework calls the "target" of an AOP method invocation.* @return the target object which contains the joinpoint,* or {@code null} if there is no actual target instance* @throws Exception if the target object can't be resolved* 返回目标对象的实例*/@NullableObject getTarget() throws Exception;/*** Release the given target object obtained from the* {@link #getTarget()} method, if any.* @param target object obtained from a call to {@link #getTarget()}* @throws Exception if the object can't be released*/void releaseTarget(Object target) throws Exception;}
代理对象创建的基础类
- 核心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
- Spring IOC 容器整合
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
- 与Spring bean 生命周期整合
