Spring AOP 多个切点实现:JdkDynamicAopProxy
Spring Aop 的底层生成代理类i的实现除 jdk的动态代理技术外,还用到了Cglib,不过在封装两者的设计原理上相差不大,只是底层工具不同而已。
本文只分析JdkDynamicAopProxy 是如何为一个目标方法执行织入多个切点,也就是将原本可能需要多个“代理类“实现的业务放到一个代理类中(JdkDynamicAopProxy)完成。
JdkDynamicAopProxy 本身就是一个JDK代理的InvocationHandler,spring 在调用其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);
}
Proxy.newProxyInstance(classLoader, proxiedInterfaces, this); 传入的 Handler 就是this,也就是 一个 JdkDynamicAopProxy 对象。所以代理的业务就在 JdkDynamicAopProxy
的 invoke()方法上。
/**
* Implementation of <code>InvocationHandler.invoke</code>.
* <p>Callers will see exactly the exception thrown by the target,
* unless a hook method throws an exception.
*/
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 {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
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...
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.
if (retVal != null && retVal == target && method.getReturnType().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;
}
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// Must have come from TargetSource.
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
invoke方法中的红色加粗代码就是重点部分: List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
该行代码是构建代理链,获取到目标方法需要增强的一系列业务代理对象。 invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
通过将目标方法和 多个业务代理对象 创建成一个 ReflectiveMethodInvocation,来实际完成 执行目标方法时执行一些拦截器,也就是代理业务。 retVal = invocation.proceed();
该行代码开始执行代理业务和目标方法。 下面是ReflectiveMethodInvocation 的 proceed方法代码:
public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
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 {
// 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);
}
}
可以看到proceed()方法通过从interceptorsAndDynamicMethodMatchers(list)集合中取出拦截器,拦截器是在前面创建ReflectiveMethodInvocation对象时传入的chain,
通过判断拦截器集合中所有拦截器是否执行完,未执行完这递归调用proceed()方法,执行完则执行目标方法。
以上就是JdkDynamicAopProxy实现多个拦截器拦截目标方法的动态代理业务。
Spring AOP 多个切点实现:JdkDynamicAopProxy的更多相关文章
- Spring AOP中定义切点(PointCut)和通知(Advice)
如果你还不熟悉AOP,请先看AOP基本原理,本文的例子也沿用了AOP基本原理中的例子.切点表达式 切点的功能是指出切面的通知应该从哪里织入应用的执行流.切面只能织入公共方法.在Spring AOP中, ...
- Spring学习(十六)----- Spring AOP实例(Pointcut(切点),Advisor)
在上一个Spring AOP通知的例子,一个类的整个方法被自动拦截.但在大多数情况下,可能只需要一种方式来拦截一个或两个方法,这就是为什么引入'切入点'的原因.它允许你通过它的方法名来拦截方法.另外, ...
- [转]彻底征服 Spring AOP 之 实战篇
Spring AOP 实战 看了上面这么多的理论知识, 不知道大家有没有觉得枯燥哈. 不过不要急, 俗话说理论是实践的基础, 对 Spring AOP 有了基本的理论认识后, 我们来看一下下面几个具体 ...
- 161110、彻底征服 Spring AOP 之 实战篇
Spring AOP 实战 看了上面这么多的理论知识, 不知道大家有没有觉得枯燥哈. 不过不要急, 俗话说理论是实践的基础, 对 Spring AOP 有了基本的理论认识后, 我们来看一下下面几个具体 ...
- Spring aop 注解参数说明
在spring AOP中,需要使用AspectJ的切点表达式语言来定义切点. 关于Spring AOP的AspectJ切点,最重要的一点是Spring仅支持AspectJ切点指示器(pointcut ...
- 彻底征服 Spring AOP 之 实战篇
Spring AOP 实战 看了上面这么多的理论知识, 不知道大家有没有觉得枯燥哈. 不过不要急, 俗话说理论是实践的基础, 对 Spring AOP 有了基本的理论认识后, 我们来看一下下面几个 ...
- spring aop实现权限管理
问题源于项目开发 最近项目中需要做一个权限管理模块,按照之前同事的做法是在controller层的每个接口调用之前上做逻辑判断,这样做也没有不妥,但是代码重复率太高,而且是体力劳动,so,便有了如题所 ...
- Spring AOP 面向切面的Spring
定义AOP术语 描述切面的常用术语有: 通知 (advice) 切点 (pointcut) 连接点 (joinpoint) 下图展示了这些概念是如何关联的 Spring 对AOP的支持 Spring提 ...
- Spring AOP 实战运用
Spring AOP 实战 看了上面这么多的理论知识, 不知道大家有没有觉得枯燥哈. 不过不要急, 俗话说理论是实践的基础, 对 Spring AOP 有了基本的理论认识后, 我们来看一下下面几个具体 ...
随机推荐
- REDIS中加锁和解锁问题
使用lua+redis的方法.之所以使用lua是为了保证原子性 问题: 1. redis发现锁失败了要怎么办?中断请求还是循环请求?2. 循环请求的话,如果有一个获取了锁,其它的在去获取锁的时候,是不 ...
- 使用idea创建第一个springboot项目
版权声明:版权归作者所有,转载请注明出处. https://blog.csdn.net/qq_34205356/article/details/81098354 前言:如今springboot越来越火 ...
- Jmeter之__CSVRead随机读取变量
背景:当你需要从一些数据中随机的取值用的话可以用这个函数来实现__CSVRead __CSVRead函数用于对脚本进行参数化,当脚本中不同变量需要不同参数值时,可以考虑__CSVRead函数. _CS ...
- 重装Mac系统
首先介绍重装macos的一些重要事项: 重装系统之前需要弄清楚本机上安装的系统版本. 重装系统是需要管理员账户的. 获取系统镜像有多种方式,其中最常见的方式是从appstore中获取,但要注意的是要确 ...
- 详解 C++11 lambda表达式
详解 C++11 lambda表达式 lambda表达式是函数式编程的基础.咱对于函数式编程也没有足够的理解,因此这里不敢胡言乱语,有兴趣的可以自己查找相关资料看下.这里只是介绍C++11中的la ...
- 手机wifi连上Fiddler后无网络问题解决
早上老板交代一个任务,对一款app抓包分析下接口调用的时延.我的重新打开了一年多前用过的Fiddler(参见win10笔记本用Fiddler对手机App抓包),拿过测试手机开始设置wifi代理地址和端 ...
- MD5Encrypt加密
package utils; import java.security.MessageDigest; public class MD5Encrypt { public MD5Encrypt() { } ...
- 利用 Postman 中 Tests 断言校验返回结果
前言 Postman目前是一款很火的接口测试工具,它有着非常强大结果判断能力.为什么说强大呢,因为Postman有自带的校验脚本,根本不需要我们去学习JS脚本语言,对于代码能力为0的各位测试小伙伴来说 ...
- iOS App Store网址的命名规则
App Store 命名规则:https://itunes.apple.com/cn/app/ + 拼音(最多6个,全部小写,空格要-) + /id +appID 一些参考实例: http:// ...
- mybatis 枚举typeHandler
枚举typeHandler 在绝大多数情况下,typeHandler因为枚举而使用,MyBatis已经定义了两个类作为枚举类型的支持,这两个类分别是: •EnumOrdinalTypeHandler. ...