SPRING 阅读--JdkDynamicAopProxy
public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
Assert.notNull(config, "AdvisedSupport must not be null");
if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
throw new AopConfigException("No advisors and no TargetSource specified");
}
this.advised = config;
}
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false; // 通过this.advised得到代理的目标类,
TargetSource targetSource = this.advised.targetSource;
Object target = null; try {
// 如何代理接口没有定义equals方法,则调用JdkDynamicAopProxy的重写的equals方法
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
// 如何代理接口没有定义equals方法,则调用JdkDynamicAopProxy的重写的equals方法
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
//如果该方法申明类是DecoratingProxy,则直接最终的被代理类的类Class
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
//如果目标对象是Advice类型,则直接使用反射进行调用
//opaque-->标记是否需要阻止通过该配置创建的代理对象转换为Advised类型,默认值为false,表示代理对象可以被转换为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;
// 看是否需要暴露代理对象,如果需要放到threadLocal上
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
} // Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null); // 得到该调用方法的拦截链
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.
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// 否则创建 MethodInvocation 执行拦截调用
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.
// 如果返回值是this,那么返回值替换为代理对象,而不是原对象。
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);
}
}
}
static Class<?>[] completeProxiedInterfaces(AdvisedSupport advised, boolean decoratingProxy) {
Class<?>[] specifiedInterfaces = advised.getProxiedInterfaces();
// 首先得到用户设置的代理接口,如果没有检查和设置代理类是否是一个接口
if (specifiedInterfaces.length == 0) {
// No user-specified interfaces: check whether target class is an interface.
Class<?> targetClass = advised.getTargetClass();
if (targetClass != null) {
if (targetClass.isInterface()) {
advised.setInterfaces(targetClass);
}
else if (Proxy.isProxyClass(targetClass)) {
advised.setInterfaces(targetClass.getInterfaces());
}
specifiedInterfaces = advised.getProxiedInterfaces();
}
}
// 如果用户代理的接口设置中没有SpringProxy接口,需要把代理类实现SpringProxy接口,该接口是个标记接口,说明是Spring代理
boolean addSpringProxy = !advised.isInterfaceProxied(SpringProxy.class);
// 如果代理类可以转化为Advised类型,并且用户没有指定Advised,则添加该接口,
//所以这里可以知道一般Spring的代理类都实现了该Advised接口
boolean addAdvised = !advised.isOpaque() && !advised.isInterfaceProxied(Advised.class);
//如果decoratingProxy==true,并且用户未添加DecoratingProxy接口,则代理需要实现该接口DecoratingProxy
boolean addDecoratingProxy = (decoratingProxy && !advised.isInterfaceProxied(DecoratingProxy.class));
int nonUserIfcCount = 0;
if (addSpringProxy) {
nonUserIfcCount++;
}
if (addAdvised) {
nonUserIfcCount++;
}
if (addDecoratingProxy) {
nonUserIfcCount++;
}
Class<?>[] proxiedInterfaces = new Class<?>[specifiedInterfaces.length + nonUserIfcCount];
System.arraycopy(specifiedInterfaces, 0, proxiedInterfaces, 0, specifiedInterfaces.length);
int index = specifiedInterfaces.length;
if (addSpringProxy) {
proxiedInterfaces[index] = SpringProxy.class;
index++;
}
if (addAdvised) {
proxiedInterfaces[index] = Advised.class;
index++;
}
if (addDecoratingProxy) {
proxiedInterfaces[index] = DecoratingProxy.class;
}
// 所以从上面分析得知,proxiedInterfaces会返回用户制定的代理接口+SpringProxy、Advised、DecoratingProxy
return proxiedInterfaces;
}
public interface Human {
Human getInstance();
}
public class ChineseHuman implements Human { private String desc; public ChineseHuman() {
} public ChineseHuman(String desc) {
this.desc = desc;
} public String getDesc() {
return desc;
} public void setDesc(String desc) {
this.desc = desc;
} @Override
public Human getInstance() {
System.out.println("human desc:" + desc);
return this;
}
}
public class JdkDynamicAopProxyTests { @Test
public void testJdkProxy() {
AdvisedSupport advisedSupport = new AdvisedSupport();
advisedSupport.setInterfaces(Human.class);
advisedSupport.setTargetSource(new TargetSource() {
@Override
public Class<?> getTargetClass() {
return ChineseHuman.class;
} @Override
public boolean isStatic() {
return false;
} @Override
public Object getTarget() throws Exception {
return new ChineseHuman("中国人");
} @Override
public void releaseTarget(Object target) throws Exception { }
});
JdkDynamicAopProxy jdkDynamicAopProxy = new JdkDynamicAopProxy(advisedSupport); Human human = (Human) Proxy.newProxyInstance(JdkDynamicAopProxy.class.getClassLoader(), new Class[]{Human.class}, jdkDynamicAopProxy); System.out.println(human.getInstance()); // JDK原生代理,必然为true,因为本身是生成的是代理的接口的对象
System.out.println("human instanceof Human:" + (human instanceof Human)); //false
System.out.println("human instanceof ChineseHuman:" + (human instanceof ChineseHuman));
//false
System.out.println("human instanceof Advised:" + (human instanceof Advised));
//false
System.out.println("human instanceof SpringProxy:" + (human instanceof SpringProxy));
//false
System.out.println("human instanceof DecoratingProxy:" + (human instanceof DecoratingProxy));
//true, 有个面试题是这么问的,java动态代理为啥代理是接口,不能是类,
// 其根原在于JDK的动态代理实现方式是代理对象继承了java.lang.reflect.Proxy,并且java单继承,所以无法代理类
System.out.println("human instanceof Proxy:" + (human instanceof Proxy)); System.out.println("Spring JDK代理扩展========="); human = (Human) jdkDynamicAopProxy.getProxy(); System.out.println(human.getInstance()); // 该代理对象的getInstance返回是其本身,原因也在于上面分析的红色部分原因。
System.out.println("human== human.getInstance():" + (human == human.getInstance())); // true
System.out.println("human instanceof Human:" + (human instanceof Human));
//false
System.out.println("human instanceof ChineseHuman:" + (human instanceof ChineseHuman));
//true
System.out.println("human instanceof Advised:" + (human instanceof Advised));
// true
System.out.println("human instanceof SpringProxy:" + (human instanceof SpringProxy));
// true
System.out.println("human instanceof DecoratingProxy:" + (human instanceof DecoratingProxy));
//true
System.out.println("human instanceof Proxy:" + (human instanceof Proxy));
}
}
从上面的测试可以知道,一个对象被Spring的JDK动态代理后,其代理对象会实现其用户指定的代理接口外,还会实现Advised,SpringProxy,DecoratingProxy接口。
SPRING 阅读--JdkDynamicAopProxy的更多相关文章
- Spring阅读方法
转自:http://www.cnblogs.com/xing901022/p/4178963.html 最近没什么实质性的工作,正好有点时间,就想学学别人的代码.也看过一点源码,算是有了点阅读的经验, ...
- Java最新趋势之Spring阅读
(原文地址:点我) This Week in Spring: Cloud Native and the State of Java This compilation of news and tutor ...
- Sping学习笔记(一)----Spring源码阅读环境的搭建
idea搭建spring源码阅读环境 安装gradle Github下载Spring源码 新建学习spring源码的项目 idea搭建spring源码阅读环境 安装gradle 在官网中下载gradl ...
- spring applicationContext.xml和hibernate.cfg.xml设置
applicationContext.xml配置 <?xml version="1.0" encoding="UTF-8"?> <beans ...
- 基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)到底有什么区别。
基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)到底有什么区别. 我还是喜欢基于Schema风格的Spring事务管理,但也有很多人在用基于@Tras ...
- Spring -- <tx:annotation-driven>注解基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)的区别。
借鉴:http://jinnianshilongnian.iteye.com/blog/1508018 基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional ...
- Spring <tx:annotation-driven>注解 JDK动态代理和CGLIB动态代理 区别。
基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)到底有什么区别. 我还是喜欢基于Schema风格的Spring事务管理,但也有很多人在用基于@Tras ...
- 全网最新最详细最明白教程之Spring源码搭建,没有之一,超详细
相关帖子有很多但是都不是最新的Gradle,我在使用Gradle最新版编译的时候简直坑死我了,弄了好久.接下来给大家详细说一下这个安装过程,以及相关的软件版本号. 相关软件.依赖的版本号: Gradl ...
- Confluence 使用常见问题列表
Confluence 6 管理 Atlassian 提供的 App 摘要: Confluence 用户可以使用桌面应用来编辑一个已经上传到 Confluence 的文件,然后这个文件自动保存回 Con ...
随机推荐
- 如何获取自定义meta标签信息?
<meta name="apple-itunes-app" content="app-id=432274380" /> 类似于这种meta信息,js ...
- node+ajax实战案例(6)
8.删除客户 8.1.发送id到后台 删除用户信息比较简单,只需要把对应行的id发送到后台就可以了 oTable.onclick = function (ev) { var ev = ev || ev ...
- 程序员的修炼-我们为什么会编写BUG
在最近的一周,我维护的业务系统出现了很多坏毛病,一周七天crash掉了4次,每次都需要都是因为一点很小的问题,触发了蝴蝶效应,导致整个系统全盘崩溃,于是产生除了叙述本篇的想法,当然这并不是为了掩盖我在 ...
- 【k8s学习笔记】使用 kubeadm 部署 v1.18.5 版本 Kubernetes集群
说明 本文系搭建kubernetes v1.18.5 集群笔记,使用三台虚拟机作为 CentOS 测试机,安装kubeadm.kubelet.kubectl均使用yum安装,网络组件选用的是 flan ...
- 调试HotSpot源代码
之前的文章在Ubuntu 16.04上编译OpenJDK8的源代码 已经介绍过在Ubuntu上编译OpenJDK8的源代码,这一篇将介绍在Ubuntu上调试OpenJDK8源代码的2种方式. 1.GD ...
- css3 斜切角/斜边的实现方式来自BAT大神的出品
设计图含有斜切角的效果时,我们一般想到的方法是切出四个角为背景,然后用border连起来,这样就能显示出该效果了,那么直接使用css呢?下面就整理css做斜边的效果. 1.方案一:利用linear-g ...
- 蓝桥杯javaB组入坑
蓝桥杯Java B组 准备工作 练习入口 | 准备资料 | 查阅说明 编辑环境 我们建议您使用大赛指定的编辑环境来编写你的代码,以保证评测时和我们的编译环境一致,同时和比赛时使用的环境也一致. 推荐的 ...
- kibana限制用户只具备读图的权限
假设需求 因为业务需要将日志系统收集到的信息进行图表化展示并交付到用户进行业务交流. 解决方案 这个需求看着似乎蛮简单的,如何解决? 1.对需要的数据进行过滤制作图表 2.对用户的权限限制为只读级别, ...
- display:inline-block 什么时候不会显示间隙?
移除空格 使用margin负值 使用font-size:0 letter-spacing word-spacing
- requests接口自动化9-共享session和传递cookie
前言: session:用requests.session()创建会话,可以将会话信息传递给其他接口 cookie:用RequestsCookieJar或者cookie字典传递cookie信息 fil ...