在分析Spring AOP之前,需要先理解AOP的术语,并理解它们代表的含义:
-
Advice:切面,切面是一个横切关注点的模块化,比如事务管理,日志处理是两个切面
-
JoinPoint:连接点,在Spring AOP中一个连接点总是代表一个方法的执行,其实AOP拦截的方法就是一个连接点
-
Advise:通知,在切面的某个连接点上执行的动作,通知类型包括“before”、“after”、“around”等。通知是指一个方法被AOP拦截到的时候要执行的代码
-
PointCut:切入点,切入点是对连接点进行拦截的条件定义
-
Target:目标对象,将要被增强的对象
-
Weaving:织入,织入是将切面和业务逻辑对象连接起来, 并创建通知代理的过程。织入可以在编译时,类加载时和运行时完成。在编译时进行织入就是静态代理,而在运行时进行织入则是动态代理
我相信,上面的描述,是足够清晰的。我们要搞清楚的一点是,上面的这些,最终目的就是为了找到某些方法,然后为这些方法生成代理类,并把方法的执行委托给代理类,让代理类在方法执行时机,执行其他动作,比如打日志,为方法启动事务等
看源码的目的不是为了面面俱到的了解框架,而是了解其主线设计,所以我们对Spring AOP这篇文章,也不会讲很多细节,而是把主线讲清楚,就达到目的了
下面将从ConcurrencyThrottleInterceptorTests测试类入手
有时候,我觉得从测试类作为入口,去了解代码,是个不错的突破点
testSerializable
先看一下testSerializable单测方法
@Test
public void testSerializable() throws Exception {
// DerivedTestBean继承TestBean,TestBean有个age属性
DerivedTestBean tb = new DerivedTestBean();
// 代理类工厂
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setInterfaces(ITestBean.class);
// 拦截器
ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor();
// 添加切面,而这个切面就是ConcurrencyThrottleInterceptor拦截器
proxyFactory.addAdvice(cti);
// 添加目标类
proxyFactory.setTarget(tb);
// 生成代理类
ITestBean proxy = (ITestBean) proxyFactory.getProxy();
// 执行代理类方法
proxy.getAge();
// 省略
}
复制代码
整个流程挺清晰,由代理类工厂生成代理类,并为代理类工厂配置切面和目标类。这里可能会有个疑问,拦截器和切面有什么关系?
从这个继承图可以看到,MethodInterceptor继承了Advice,从这个角度来说,拦截器就是切面,另外还有其他的切面,比如AfterReturningAdvice,在方法返回后执行
ProxyFactory
ProxyFactory继承ProxyCreatorSupport,ProxyCreatorSupport是代理类工厂的基类,为访问AopProxyFactory提供了方便的操作,其内部也持有AopProxyFactory实例
比如最常用的getProxy()方法,就是创建通过AopProxyFactory返回代理类,而这个动作就在ProxyCreatorSupport的createAopProxy()方法里。
protected final synchronized AopProxy createAopProxy() {
// 判断Spring AOP是否已被创建,如果未创建过,则设置为true
if (!this.active) {
activate();
}
// 这里创建AopProxyFactory实例,并返回AopProxy代理类
return getAopProxyFactory().createAopProxy(this);
}
复制代码
DefaultAopProxyFactory
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
// 两种AopProxy,接口就返回JdkDynamicAopProxy,类就返回ObjenesisCglibAopProxy
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
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.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
复制代码
从名字可以看出ObjenesisCglibAopProxy是通过cglib生成的AopProxy,JdkDynamicAopProxy是通过jdk的动态代理生成AopProxy,这里我们看JdkDynamicAopProxy就行了
JdkDynamicAopProxy
JdkDynamicAopProxy实现了AopProxy接口,和InvocationHandler接口,用来创建动态代理类。我们知道在ProxyFactory的getProxy()方法,调用的就是JdkDynamicAopProxy的getProxy(),这个方法就是通过JDK Proxy的newProxyInstance创建代理类,如果直观一点看的话,是下面这样的
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isDebugEnabled()) {
logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
}
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
复制代码
生成的动态代理类类名是$Proxy20@1991,因为Proxy.newProxyInstance传的InvocationHandler是this,也就是JdkDynamicAopProxy自身,所以h是JdkDynamicAopProxy实例。从上面的代码还知道,我们要代理的目标类,是来自于AdvisedSupport配置,AdvisedSupport继承ProxyConfig,关于这些配置,不是关注的重点,所以跳过......
到这里,代理类已经生成了,接下来就是调用代理类的方法了,在单测里,是proxy.getAge(),会被代理到JdkDyn-amicAopProxy的invoke()
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
// 目标类
Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
// 返回值
Object retVal;
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// 从TargetSource的对象池中获取目标类
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
// 获取拦截器链
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
if (chain.isEmpty()) {
// 如果拦截器链为空,就直接执行方法
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// 如果拦截器链不为空,就通过MethodInvocation来执行目标方法和拦截器链
invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// Proceed to the joinpoint through the interceptor chain.
retVal = invocation.proceed();
}
// Massage return value if necessary.
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target &&
returnType != Object.class && returnType.isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// Special case: it returned "this" and the return type of the method
// is type-compatible. Note that we can't help if the target sets
// a reference to itself in another returned object.
retVal = proxy;
}
else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method);
}
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// Must have come from TargetSource.
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
复制代码
这里关键是获取拦截器链,因为拦截器里包装了我们想要的增强的功能
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
// 先从缓存获取
MethodCacheKey cacheKey = new MethodCacheKey(method);
List<Object> cached = this.methodCache.get(cacheKey);
if (cached == null) {
// 通过AdvisorChainFactory获取拦截器链,然后再放在缓存
cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
this, method, targetClass);
this.methodCache.put(cacheKey, cached);
}
return cached;
}
复制代码
因为我们设置拦截器只有ConcurrencyThrottleInterceptor对象,所以这里返回的就是只有一个元素的list,而这个元素就是ConcurrencyThrottleInterceptor对象。
我们再看ReflectiveMethodInvocation,最终是执行它的proceed(),ReflectiveMethodInvocation其实是个中间桥梁,粘接了target方法和拦截器方法,我们看一下proceed()
public Object proceed() throws Throwable {
// 如果拦截器链方法都执行完,就执行invokeJoinpoint()
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
// 获取下一个拦截器,从0开始顺序获取
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
}
else {
// Dynamic matching failed.
// Skip this interceptor and invoke the next in the chain.
return proceed();
}
}
else {
// 执行拦截器
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
复制代码
执行拦截器方法,又会继续执行当前方法,以为invoke方法传递的是this对象,所以拦截器执行完后,最终执行的是invokeJoinpoint(),而这个方法也挺简单,调用的是AopUtils.invokeJoinpointUsingReflection()
至此,整个思路已经梳理出来了
但还是有个疑问,就是我们平时使用切面,是由Spring框架启动的,而上面是有单测的ProxyFactory的,那Spring框架又是如何启动AOP的呢,换句话就是,Spring如何扩展AOP?
答案就是FactoryBean,还记得在讲Spring IoC讲过,很多功能的扩展是通过FactoryBean来实现的,Spring AOP也是,具体是通过ProxyFactoryBean来实现的
ProxyFactoryBean
我们直接看getObject()方法
public Object getObject() throws BeansException {
// 初始化拦截器链
initializeAdvisorChain();
if (isSingleton()) {
// 返回单例代理类
return getSingletonInstance();
}
else {
if (this.targetName == null) {
logger.warn("Using non-singleton proxies with singleton targets is often undesirable. " +
"Enable prototype proxies by setting the 'targetName' property.");
}
// 返回原型代理类
return newPrototypeInstance();
}
}
复制代码
getSingletonInstance()的创建逻辑,就是上面分析的,这里就不再重复了。
总结
Spring AOP的原理就是通过AOP配置生成拦截器链,并为目标方法生成代理类,并把方法的执行委托给代理类,当执行代理类方法时,先触发拦截器链,所有拦截器执行完毕,再执行目标方法。