1. Spring Aop 编程式Aop Demo
整个 "编程式Aop"的参与者如下: 被代理的对象, 方法拦截器 MethodInterceptor, 代理工厂创建者 ProxyFactory; 下面是一个简单的 Demo:
// 代理类
public class KK implements Person {
@Override
public String doSomething() {
return "OK";
}
}
// 代理类实现的接口
interface Person {
String doSomething();
}
// 执行的 MethodBeforeAdvice
class SimpleBeforeAdvice implements MethodBeforeAdvice{
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("Currently Processing " + method);
}
}
// 执行的 MethodInterceptor
class SimpleMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
invocation.proceed();
return "SimpleBeforeAdvice";
}
}
class ProxyFactoryTest {
public static void main(String[] args) {
// 被代理的类
KK kk = new KK();
// 创建 Proxy 的工厂类
ProxyFactory proxyFactory = new ProxyFactory(kk);
// 代理类中要运用的 Advice
SimpleBeforeAdvice simpleBeforeAdvice = new SimpleBeforeAdvice();
// 代理类中要运用的 MethodInterceptor
SimpleMethodInterceptor simpleMethodInterceptor = new SimpleMethodInterceptor();
// 给 proxyFactory 添加 Advice
proxyFactory.addAdvice(simpleBeforeAdvice);
proxyFactory.addAdvice(simpleMethodInterceptor);
// 通过 proxyFactory 创建 代理类
Person nKK = (Person)proxyFactory.getProxy();
// 执行代理类的方法
nKK.doSomething();
}
}
整体上编程式 aop 还是蛮简单的, 见上, 将需要代理的类放入ProxyFactory中, 并设置对应的 Advice 或 MethodInterceptor 就 OK 了, 下面我们将一步一步解析整个过程中 ProxyFactory 及 代理类执行过程!
2. Spring Aop 创建 aop 过程概述
从上面的代码得知整个创建过程都封装在 ProxyFactory 的内部, 关于 ProxyFactory 的内部组织结构如下:
上面图中主要有如下组件:
1. ProxyConfig: 动态代理创建的配置类, 其主要有: proxyTargetClass(是否强制使用 CGlib 生成代理类), optimize(是否使用优化方式创建代理类, 基于 CGlib创建的代理类的执行速度比基于动态创建的类执行速度快, 所以optimize在这里也表示是否使用 CGLib 方式创建动态代理类), opaque(中文意思是: 不透明,这里的透明指透明到 Advised 中, 其实指的是是否将 Advised 暴露出去供外界调用), exposeProxy(是否将实现了的代理类暴露到 ThreadLocal 中供外界调用), frozen(冻结, 这里的冻结指针对Advised里面的属性, 若 frozen = true, 则表示不能再改变 Advised 中的属性)
2. Advised: 这个接口主要的实现者就是ProxyFactory, 这个接口中定义了 Advice/Advisor 等操作的方法
3. AdvisedSupport: 这个类实现了接口 Advised, 并对其中的接口进行了实现(PS: 主要是 针对 Advice/Advisor 的操作)
4. DefaultAopProxyFactory: 默认的 AopProxy 工厂创建类, 它根据 ProxyConfig 中的配置信息来选择合适的 AopProxy(主要是 JdkDynamicAopProxy 与 ObjenesisCglibAopProxy)
5. JdkDynamicAopProxy: 这个类主要完成了 动态代理类的创建, 实现了 InvocationHandler接口, 根据AdvisedSupport中配置的属性及 Advice/Advisor 来完成ReflectiveMethodInvocation的封装及调用流程(ReflectiveMethodInvocation的调用是递归调用)
6. ReflectiveMethodInvocation: 这个类封装了动态代理类, 真实类, 执行的方法, 方法的参数, 执行的 MethodInterceptor, 其主要执行流程是先递归的调用 MethodInterceptor, 最后通过反射调用目标对象的目标方法
7. DefaultAdvisorChainFactory: 它主要是根据 class, method 来从 Advised 中获取符合条件的 MethodInterceptor, 并组装成链表
8. ProxyCreatorSupport: 这个类通过 AopProxyFactory 来完成 AopProxy 的创建, 增加AdvisedSupportListener的支持
9. ProxyFactory: 完成动态代理类的创建, 通过设置一个目标类来完成动态代理类的创建
以上是创建动态类过程中涉及的工具类, 下面的步骤中涉及!
3. Spring Aop 创建 aop 主过程
整个创建的过程不复杂, 主要是如下步骤:
1. 将 ProxyFactory 中的激活标示 active = true, 通过 AdvisedSupportListener 来回调 AdvisedSupport (这个 AdvisedSupportListener 默认没有实现类)
2. DefaultAopProxyFactory 根据 AdvisedSupport 来创建 对应的 AopProxy (JdkDynamicAopProxy 或 ObjenesisCglibAopProxy)
3. JdkDynamicAopProxy 创建 代理类, 这里的 InvocationHandler 其实就是 JdkDynamicAopProxy 本身
与之对应的时序图如下:
其中 进行刷选合适的 AopProxy 逻辑相对多一点:
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
// 启用了 优化配置(原因就是 cglib 的性能比 JDK Proxy 要好) || 启用了直接代理目标类模式 || 没有指定要代理的接口(除了 接口SpringProxy)
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.");
}
// 代理的对象是否是接口 或 targetClass 是否是 java.lang.reflect.Proxy 的子类
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
// 创建 cglib 代理的工厂对象
return new ObjenesisCglibAopProxy(config);
}
else {
// 返回创建 JDK 代理的工厂对象
return new JdkDynamicAopProxy(config);
}
}
4. Spring Aop 动态代理对象执行过程 -> 代理类
首先经过上面这些代码, 我们最终创建的是类似如下的动态代理类:
final class $Proxy0 extends Proxy
implements Person, SpringProxy, Advised
{
private static Method m1;
// 构造函数 这里的 paramInvocationHandler 其实就是我们这里的 JdkDynamicAopProxy
public $Proxy0(InvocationHandler paramInvocationHandler)
{
super(paramInvocationHandler);
}
static
{
try
{ // 获取对应的 method (PS: 这里就是方法 doSomething )
m1 = Class.forName("com.lami.foodie.aop.aop1.Person").getMethod("doSomething", new Class[0]);
return;
}
catch (Exception e)
{}
}
public final String doSomething()
{
try
{ // 将 doSomething 的激活交给 paramInvocationHandler -> 其实就是 JdkDynamicAopProxy
return (String)this.h.invoke(this, m1, null);
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
}
PS: 上面代码中省略了不需要的代码 -> 我们这里只关注 doSomething 方法 , 上面这个类是通过 HSDB这个工具类来获取, 详情 (http://rednaxelafx.iteye.com/blog/1847971)
从上面的代码中, 我们可以清楚的看到, Proxy方式创建的代理对象其实通过 InvocationHandler 这个回调来其作用, 最后还是通过反射方法(与之对比的 CGLib 是直接通过 ASM 字节码库生成对应的子类)
5. Spring Aop 动态代理对象执行过程 -> InvocationHandler
这里的 InvocationHandler 则是 JdkDynamicAopProxy, 在 JdkDynamicAopProxy的 invoke(Object proxy, Method method, Object[] args) 完成了
1. 针对 equals, hashCode 的单独处理
2. Advised 接口中的方法直接通过 AdvisedSupport 来激活
3. 将代理对象直接暴露到 ThreadLocal 中
4. 根据 Method, Class 从 AdvisedSupport 中组装合适的MethodInterceptor
5. 将 Proxy类, 被代理对象, 执行方法, 方法的参数, 其中涉及的 MethodInterceptor 封装成 ReflectiveMethodInvocation, 通过 ReflectiveMethodInvocation 来安排调用过程
其代码+注释如下:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
// 目标对象的包装类, 通过 AdvisedSupport的setTarget方法设置的会自动封闭成 TargetSource 的实现 SingletonTargetSource
TargetSource targetSource = this.advised.targetSource;
Class<?> targetClass = null;
Object target = null;
try {
// 被代理的接口中没有定义 equals 方法且目前方法是 equals 方法, 则调用 equals 方法比较两代对象所代理的接口
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
// 如果目标对象没有实现 object 类的基础方法 euqals
return equals(args[0]);
}
// hashCode 方法的处理
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
// 如果目标对象没有实现 object 类的基础方法 hashCode
return hashCode();
}
// 如果调用的方法是 DecoratingProxy声明的
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
/**
* Class类的 isAssignableFrom(Class cls) 方法:
* 自身类.class.isAssignableFrom(自身类或子类.class) 返回 true
*
* 对 Advised 接口或者子接口中的方法的调用不经过任何拦截器, 直接委托给Advised 对象中的方法
* (此 if 块 的目的是实现将 advised 对象引入代理对象), this.advised.opaque 默认情况下是 false(它只是一个开关
* 选项, 控制代理对象是否可以操作 advised)
*/
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
// 调用 advised 的method 方法
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal;
// 当目标对象内部的自我调用无法实施切面中的增强则需要增强则需要通过此属性暴露代理
if (this.advised.exposeProxy) {
// 把当前代理对象放到 AopContext 中(其内部使用 ThreadLocal 存着), 并返回上下文中原来的代理对象, 并且保留之前暴露设置的代理
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// May be null. Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
// 得到目标对象
target = targetSource.getTarget();
if (target != null) {
targetClass = target.getClass();
}
// 获取当前方法的拦截器链
// Get the interception chain for this method.
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
// Check whether we have any advice. If we don't, we can fallback on direct
// reflective invocation of the target, and avoid creating a MethodInvocation.
// 检测是否含有 MethodInterceptor
if (chain.isEmpty()) {
// 没有任何拦截器需要执行则直接执行目标对象方法
// We can skip creating a MethodInvocation: just invoke the target directly
// Note that the final invoker must be an InvokerInterceptor so we know it does
// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
/**
* 如果有拦截器的设定, 那么需要调用拦截器之后才调用目标对象的相应方法
* 通过 构造一个 ReflectiveMethodInvocation 来实现, 下面会看
* 这个 ReflectiveMethodInvocation 类的具体实现
*/
// We need to create a method invocation...
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();
// 处理返回目标对象本身的情况, 也许某些方法是返回this引用, 此时需要返回代理对象而不是目标对象
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()) { // 从这里我们可以发现, 拦截器的返回值若设定的不是 null, 但是 你主动设置为 null, 则将会报出异常
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 不是一个静态的 targetSource, 那么释放此 target, 默认的 SingletonTargetSource.isStatic 方法是 true 的
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
// 还原之前的代理对象
AopContext.setCurrentProxy(oldProxy);
}
}
}
6. Spring Aop 动态代理对象执行过程 -> ReflectiveMethodInvocation
ReflectiveMethodInvocation: 这个类主要完成了动态代理的执行过程控制:
1. 递归的执行ReflectiveMethodInvocation.process()方法, 每次递归执行的其实是上层封装 MethodInterceptor
2. 当上述 MethodInterceptor 递归执行完后, 则通过 invokeJoinpoint() 来反射在目标对象上执行对应的方法
对应的主逻辑代码如下:
public Object proceed() throws Throwable {
// 执行完所有增强执行切点方法
// currentInterceptorIndex 默认等于 -1 的, 它记录着当前执行到了哪个拦截器
// interceptorsAndDynamicMethodMatchers 代表着匹配了的 MethodInterceptor
// We start with an index of -1 and increment early.
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
// 如果所有的 拦截器都执行完了的话, 则调用 invokeJoinPoint 方法去执行目标对象的目标方法 (反射)
return invokeJoinpoint();
}
// 得到当前要执行的拦截器(拦截器是顺序执行的 )
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
// 下面判断当前拦截器是不是一个动态拦截器
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) { // 其实在 Spring 中 主要的实现类是 AspectJExpressionPointcut
// 动态 匹配 方法 拦截
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
// 这里调用 MethodMatcher 类中带3个参数的 matches 方法
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 {
// 将 this作为参数(MehtodInvocation)传递以保证当前实例中调用链的执行
// It's an interceptor, so we just invoke it: The pointcut will have
// been evaluated statically before this object was constructed.
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
6. 总结
上面的 Aop 执行过成其实是整个 Aop 中的核心, 只要掌握了这几个核心类, 会发现 aop 在 Spring 中的实现其实就是对目标类包裹一个类, 而后在每次执行目标类时先执行动态代理类, 动态代理类中先执行 MethodInterceptor, 最终才会通过反射方法来执行目标对象的目标方法
6. 参考资料
Spring技术内幕分析
Spring 5 源码分析
开涛的 Spring杂谈
伤神的 Spring源码分析
Spring源码情操陶冶
Spring 揭秘 (PS: 这本书绝对给力)
Spring 技术内幕
Spring 源码深度分析
Spring 高级程序设计 (PS:这本书已经绝版, 所以当时是自己下载 pdf, 然后联系淘宝卖家忙帮复印, 其实就是英文版本的 "Pro Spring 3")
expert one-on-one J2EE Development without EJB (PS: Spring 作者自己写的书, 当时也是下载 PDF, 联系淘宝卖家复印购买到的)