我们知道Spring是通过JDK或者CGLib实现动态代理的,今天我们讨论一下JDK实现动态代理的原理。

一、简述

Spring在解析Bean的定义之后会将Bean的定义生成一个BeanDefinition对象并且由BeanDefinitionHolder对象持有。在这个过程中,如果Bean需要被通知切入,BeanDefinition会被重新转换成一个proxyDefinition(其实也是一个BeanDefinition对象,只不过描述的是一个ProxyFactoryBean)。ProxyFactoryBean是一个实现了FactoryBean的接口,用来生成被被切入的对象。Spring AOP的实现基本上是通过ProxyFactoryBean实现的。我们今天讨论的重点也是这个类。
  在讨论ProxyFactoryBean之前,我们先看一下一个BeanDefinition转换成proxyDefintion的过程。

public final BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definitionHolder, ParserContext parserContext) {
BeanDefinitionRegistry registry = parserContext.getRegistry();

// get the root bean name - will be the name of the generated proxy factory bean
String existingBeanName = definitionHolder.getBeanName();
BeanDefinition targetDefinition = definitionHolder.getBeanDefinition();
BeanDefinitionHolder targetHolder = new BeanDefinitionHolder(targetDefinition, existingBeanName + ".TARGET");

// delegate to subclass for interceptor definition
BeanDefinition interceptorDefinition = createInterceptorDefinition(node);

// generate name and register the interceptor
String interceptorName = existingBeanName + "." + getInterceptorNameSuffix(interceptorDefinition);
BeanDefinitionReaderUtils.registerBeanDefinition(
new BeanDefinitionHolder(interceptorDefinition, interceptorName), registry);

BeanDefinitionHolder result = definitionHolder;

if (!isProxyFactoryBeanDefinition(targetDefinition)) {
// create the proxy definition 这里创建proxyDefinition对象,并且从原来的BeanDefinition对象中复制属性
RootBeanDefinition proxyDefinition = new RootBeanDefinition();
// create proxy factory bean definition
proxyDefinition.setBeanClass(ProxyFactoryBean.class);
proxyDefinition.setScope(targetDefinition.getScope());
proxyDefinition.setLazyInit(targetDefinition.isLazyInit());
// set the target
proxyDefinition.setDecoratedDefinition(targetHolder);
proxyDefinition.getPropertyValues().add("target", targetHolder);
// create the interceptor names list
proxyDefinition.getPropertyValues().add("interceptorNames", new ManagedList<String>());
// copy autowire settings from original bean definition.
proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
proxyDefinition.setPrimary(targetDefinition.isPrimary());
if (targetDefinition instanceof AbstractBeanDefinition) {
proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition);
}
// wrap it in a BeanDefinitionHolder with bean name
result = new BeanDefinitionHolder(proxyDefinition, existingBeanName);
}

addInterceptorNameToList(interceptorName, result.getBeanDefinition());
return result;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
二、ProxyFactoryBean的原理
我们先来看一下ProxyFactoryBean的继承关系:

ProxyFactoryBean实现了FactoryBean、BeanClassLoaderAware、BeanFactoryAware接口,这里就不多说了。ProxyCreatorSupport这个类则是创建代理对象的关键所在。  我们先来看看产生代理对象的方法:

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();
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
initializeAdvisorChain() 方法是将通知链实例化。然后判断对象是否要生成单例而选择调用不同的方法,这里我们只看生成单例对象的方法。

private synchronized Object getSingletonInstance() {
if (this.singletonInstance == null) {
this.targetSource = freshTargetSource();
//如果以接口的方式代理对象
if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
// Rely on AOP infrastructure to tell us what interfaces to proxy.
Class<?> targetClass = getTargetClass();
if (targetClass == null) {
throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
}
//获取目标类实现的所有接口,并注册给父类的interfaces属性,为jdk动态代理做准备
setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
}
// Initialize the shared singleton instance.
super.setFrozen(this.freezeProxy);
//这里产生代理对象
this.singletonInstance = getProxy(createAopProxy());
}
return this.singletonInstance;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
我们可以看到,产生代理对象是通过getProxy()方法实现的,这个方法我们看一下:

protected Object getProxy(AopProxy aopProxy) {
return aopProxy.getProxy(this.proxyClassLoader);
}

1
2
3
4
AopProxy对象的getProxy()方法产生我们需要的代理对象,究竟AopProxy这个类是什么,我们接下来先看一下产生这个对象的方法createAopProxy():

protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}

createAopProxy方法:
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
//目标对象不是接口类的实现或者没有提供代理接口
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()) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
在这里我们只看JdkDynamicAopProxy这个类的实现,我们前面提到,真正代理对象的生成是由AopProxy的getProxy方法完成的,这里我们看一下JdkDynamicAopProxy的getProxy方法,这也是本文讨论的重点:

public Object getProxy(ClassLoader classLoader) {
if (logger.isDebugEnabled()) {
logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
}
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}

1
2
3
4
5
6
7
8
9
我们看可以很清楚的看到,代理对象的生成直接使用了jdk动态代理:Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);而代理逻辑是通过实现了InvocationHandler接口的invoke方法实现的。而这里用到的实现了InvocationHandler接口的类就是JdkDynamicAopProxy自身。JdkDynamicAopProxy自身实现了InvocationHandler接口,完成了Spring AOP拦截器链拦截等一系列逻辑,我们看一下JdkDynamicAopProxy的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;
Class<?> targetClass = null;
Object target = null;

try {
//没有重写equals方法
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
//没有重写hashCode方法
if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
//代理的类是Advised,这里直接执行,不做任何代理
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;
}

// 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.
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.
//拦截器链是空的,直接执行需要代理的方法
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);
}
else {
// We need to create a method invocation...
//这里是调用拦截器链的地方,先创建一个MethodInvocation对象,然后调用该对象的proceed方法完成拦截器链调用
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.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);
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
拦截器链的调用
从上面的代码和注释中我们可以看到spring实现aop的主要流程,具体如何调用拦截器链,我们来看一下MethodInvocation的proceed方法

public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
// currentInterceptorIndex是从-1开始的,所以拦截器链调用结束的时候index是 this.interceptorsAndDynamicMethodMatchers.size() - 1
// 调用链结束后执行目标方法
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
// 获得当前处理到的拦截器
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
// 这里判断是否是InterceptorAndDynamicMethodMatcher,如果是,这要判断是否匹配methodMatcher,不匹配则此拦截器不生效
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 {
// 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);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
proceed()方法是一个递归方法,我们可以根据代码的注释知道大体逻辑,InterceptorAndDynamicMethodMatcher的代码如下,我们可以看到,InterceptorAndDynamicMethodMatcher 持有一个MethodInterceptor 对象和一个MethodMatcher 对象,在拦截器链调用过程中,如果拦截器是InterceptorAndDynamicMethodMatcher ,则会先根据MethodMatcher 判断是否匹配,匹配MethodInterceptor 才会生效。

class InterceptorAndDynamicMethodMatcher {

final MethodInterceptor interceptor;

final MethodMatcher methodMatcher;

public InterceptorAndDynamicMethodMatcher(MethodInterceptor interceptor, MethodMatcher methodMatcher) {
this.interceptor = interceptor;
this.methodMatcher = methodMatcher;
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
至于MethodInterceptor 是什么,MethodInterceptor 的逻辑是怎么样的,我们可以看一下MethodInterceptor 的一个子类AfterReturningAdviceInterceptor的实现:

public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable { private final AfterReturningAdvice advice; /** * Create a new AfterReturningAdviceInterceptor for the given advice. * @param advice the AfterReturningAdvice to wrap */ public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } @Override public Object invoke(MethodInvocation mi) throws Throwable { Object retVal = mi.proceed(); this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis()); return retVal; }}

1
2
AfterReturningAdviceInterceptor的作用是在被代理的方法返回结果之后添加我们需要的处理逻辑,其实现方式我们可以看到,先调用MethodInvocation 的proceed,也就是先继续处理拦截器链,等调用完成后执行我们需要的逻辑:this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
到这里,spring使用jdk动态代理实现aop的分析基本上结束,其中拦截器链的调用比较难懂而且比较重要,需要的同学可以多看看这一块。
---------------------

Spring AOP --JDK动态代理方式的更多相关文章

  1. Spring AOP JDK动态代理与CGLib动态代理区别

    静态代理与动态代理 静态代理 代理模式 (1)代理模式是常用设计模式的一种,我们在软件设计时常用的代理一般是指静态代理,也就是在代码中显式指定的代理. (2)静态代理由 业务实现类.业务代理类 两部分 ...

  2. 浅谈Spring中JDK动态代理与CGLIB动态代理

    前言Spring是Java程序员基本不可能绕开的一个框架,它的核心思想是IOC(控制反转)和AOP(面向切面编程).在Spring中这两个核心思想都是基于设计模式实现的,IOC思想的实现基于工厂模式, ...

  3. Spring AOP 和 动态代理技术

    AOP 是什么东西 首先来说 AOP 并不是 Spring 框架的核心技术之一,AOP 全称 Aspect Orient Programming,即面向切面的编程.其要解决的问题就是在不改变源代码的情 ...

  4. Spring的JDK动态代理如何实现的(源码解析)

    前言 上一篇文章中提到了SpringAOP是如何决断使用哪种动态代理方式的,本文接上文讲解SpringAOP的JDK动态代理是如何实现的.SpringAOP的实现其实也是使用了Proxy和Invoca ...

  5. AOP jdk动态代理

    一: jdk动态代理是Spring AOP默认的代理方法.要求 被代理类要实现接口,只有接口里的方法才能被代理,主要步骤是先创建接口,接口里创建要被代理的方法,然后定义一个实现类实现该接口,接着将被代 ...

  6. SSM-Spring-09:Spring中jdk动态代理

    ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- JDK动态代理: 为何叫JDK动态代理呢? 所谓JDK,jdk是java开发工具包,它里面包含了一个动态代理的 ...

  7. Spring AOP之动态代理

    软件151 李飞瑶 一.Spring 动态代理中的基本概念  1.关注点(concern)    一个关注点可以是一个特定的问题,概念.或者应用程序的兴趣点.总而言之,应用程序必须达到一个目标    ...

  8. Spring AOP 前奏--动态代理

  9. Cglib 与 JDK动态代理

    作者:xiaolyuh 时间:2019/09/20 09:58 AOP 代理的两种实现: jdk是代理接口,私有方法必然不会存在在接口里,所以就不会被拦截到: cglib是子类,private的方法照 ...

随机推荐

  1. ZooKeeper可以用来做什么(转)

    在ZooKeeper的官网上有这么一句话:ZooKeeper is a centralized service for maintaining configuration information, n ...

  2. 完全卸载VS2015的方法

    解压ISO文件夹,到根目录下运行命令行: vs_enterprise.exe /uninstall /force 注意:如果安装了Update 3时,就解压最新的ISO,不需要旧的. 卸载完成之后,删 ...

  3. (七)CAS 本地localhost调试,无法单点退出疑问

            干活的时候要多思考-------- 题记          昨天下午接到任务把内容汇聚平台和分发平台加上统一认证登录,之前弄过CAS,想想这个过程也就是按部就班的事情.在两个系统中we ...

  4. 【Java集合源代码剖析】Hashtable源代码剖析

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/36191279 Hashtable简单介绍 Hashtable相同是基于哈希表实现的,相同每 ...

  5. rac_grid自检无法正常进行报PRVF-4007

    原创作品,出自 "深蓝的blog" 博客.欢迎转载,转载时请务必注明下面出处.否则追究版权法律责任. 深蓝的blog:http://blog.csdn.net/huangyanlo ...

  6. Python游戏server开发日记(一)目标

    到了新的环境.老大让我有空研究下一代server技术,作为一个长期任务. 新的server想达到的目标: 1.分布式系统,对象(Entity)之间的关系类似于Actor模型. 2.逻辑服务,是单进程. ...

  7. Python自定义钉钉机器人发送自动化结果报告

    环境python3.5+jenkins # coding:utf-8 import urllib.request import json import sys import time import r ...

  8. 集成CCFlow工作流与GPM的办公系统驰骋CCOA介绍(二)

    GPM怎样控制菜单权限以及菜单的增删显示 因为CCOA中仅仅有属于admin才干够进行权限管理与流程设计.password为pub. 1.加入CCOA功能菜单 进入GPM后,找到编号为CCOA的信息后 ...

  9. 单向链表的归并排序——java实现

    在做Coursera上的Algorithms第三周测验练习的时候有一道链表随机排序问题,刚开始没有什么思路,就想着先把单向链表归并排序实现了,再此基础上进行随机排序的改造.于是就结合归并排序算法,实现 ...

  10. 原生JS---4

    原生js学习笔记4——BOM操作 什么是DOM DOM:Do 1. js的组成部分 2. 一套标准,目前有DOM1和DOM2这两种标准 我们可以使用DOM操作来操作页面中的元素. DOM节点 子节点 ...