spring 注解aop调用invoke()
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:config" + "/spring/applicationContext-core2.xml");
MyService as = (MyService) context.getBean("annotationServiceImpl");
as.doSomething("Jack"); //aop起作用,com.zhuguang.jack.annotation.AnnotationServiceImpl@1c55f277,里面的h = org.springframework.aop.framework.JdkDynamicAopProxy@50c6911c,h里面的advised = ProxyFactory = 1 interfaces [MyService]; 4 advisors [ExposeInvocationInterceptor.ADVISOR, InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void afterrr(JoinPoint)]; InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void arounddd(ProceedingJoinPoint) ]; InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void beforeee(JoinPoint)]; ]; targetSource [AnnotationServiceImpl@1c55f277]];
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
TargetSource targetSource = this.advised.targetSource; //AnnotationServiceImpl,被代理的类,
Class<?> targetClass = null;
Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) { //调用的方法是equals方法,就直接调用了,不用代理了。
return equals(args[0]);
}
if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) { //调用的方法是hashCode方法,就直接调用了,不用代理了。
return hashCode();
}
if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {//调用的方法是,,就直接调用了,不用代理了。
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal;
target = targetSource.getTarget();
if (target != null) {
targetClass = target.getClass();//class com.zhuguang.jack.annotation.AnnotationServiceImpl
}
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); //advised = ProxyFactory代理工厂,
[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()]这些切面已经加到工厂里面去了, [ExposeInvocationInterceptor@65aa6596,
AspectJAfterAdvice: advice method [public void afterrr()]; aspect name 'aspectAnnotation',
AspectJAroundAdvice: advice method [public void arounddd() ]; aspect name 'aspectAnnotation',
MethodBeforeAdviceInterceptor@1ce61929]
else {
invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
retVal = invocation.proceed(); //调用,invocation = ReflectiveMethodInvocation,
}
Class<?> returnType = method.getReturnType(); //返回值
return retVal;
}
}
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, Class<?> targetClass) {
MethodCacheKey cacheKey = new MethodCacheKey(method); //doSomething方法,
List<Object> cached = this.methodCache.get(cacheKey);
if (cached == null) {
cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(this, method, targetClass);
this.methodCache.put(cacheKey, cached);
}
return cached;
}
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
Advised config, Method method, Class<?> targetClass) { //config = ProxyFactory,method = doSomething(),targetClass = AnnotationServiceImpl List<Object> interceptorList = new ArrayList<Object>(config.getAdvisors().length);
boolean hasIntroductions = hasMatchingIntroductions(config, targetClass);
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
for (Advisor advisor : config.getAdvisors()) {//[ExposeInvocationInterceptor.ADVISOR,
InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void afterrr()];
InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void arounddd() ];
InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void beforeee()]]
if (advisor instanceof PointcutAdvisor) {
PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor; //AspectAnnotation.afterrr,AspectAnnotation.arounddd,AspectAnnotation.beforeee,
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(targetClass)) { //在不在Pointcut的表达式里面,匹配的是类。
MethodInterceptor[] interceptors = registry.getInterceptors(advisor); //AspectAnnotation.afterrr,
MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher(); //AspectJExpressionPointcut: () pc1(),
if (MethodMatchers.matches(mm, method, targetClass, hasIntroductions)) { //前面匹配的是类,这里匹配的是方法。
else {
interceptorList.addAll(Arrays.asList(interceptors));
}
}
}
}
}
return interceptorList;
}
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
List<MethodInterceptor> interceptors = new ArrayList<MethodInterceptor>(3);
Advice advice = advisor.getAdvice();
if (advice instanceof MethodInterceptor) {
interceptors.add((MethodInterceptor) advice);
}
for (AdvisorAdapter adapter : this.adapters) {
if (adapter.supportsAdvice(advice)) {
interceptors.add(adapter.getInterceptor(advisor));
}
}
return interceptors.toArray(new MethodInterceptor[interceptors.size()]);
}
public Object proceed() throws Throwable {
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) { //索引是最后一个就调用被代理类的方法,interceptorsAndDynamicMethodMatchers = [ExposeInvocationInterceptor.ADVISOR,
InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void afterrr()];
InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void arounddd() ];
InstantiationModelAwarePointcutAdvisor: expression [pc1()]; advice method [public void beforeee()]]
return invokeJoinpoint(); //被代理类的方法
} Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex); //根据索引拿到第一个,第二个,。。 else {
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this); //链是调用,this = invocation = ReflectiveMethodInvocation,
}
}
ExposeInvocationInterceptor类的invoke()方法
public Object invoke(MethodInvocation mi) throws Throwable {
MethodInvocation oldInvocation = invocation.get();
invocation.set(mi);
try {
return mi.proceed(); //mi = invocation = ReflectiveMethodInvocation,又调会去了,拿到第二个。
}
finally {
invocation.set(oldInvocation);
}
}
AspectAnnotation.afterrr(org.aspectj.lang.JoinPoint) 类:
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed(); //mi = invocation = ReflectiveMethodInvocation,又调会去了,拿到第三个。after所以现在不会执行。
}
finally {
invokeAdviceMethod(getJoinPointMatch(), null, null);
}
}
AspectAnnotation.arounddd(org.aspectj.lang.ProceedingJoinPoint)类
public Object invoke(MethodInvocation mi) throws Throwable {
ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;//mi = invocation = ReflectiveMethodInvocation,
ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi);
JoinPointMatch jpm = getJoinPointMatch(pmi);
return invokeAdviceMethod(pjp, jpm, null, null);
}
protected Object invokeAdviceMethod(JoinPoint jp, JoinPointMatch jpMatch, Object returnValue, Throwable t)
throws Throwable {
return invokeAdviceMethodWithGivenArgs(argBinding(jp, jpMatch, returnValue, t));
} protected Object invokeAdviceMethodWithGivenArgs(Object[] args) throws Throwable {
try {
ReflectionUtils.makeAccessible(this.aspectJAdviceMethod);
return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs);
}
public Object invoke(Object obj, Object... args)
{
MethodAccessor ma = methodAccessor; // read volatile
if (ma == null) {
ma = acquireMethodAccessor();
}
return ma.invoke(obj, args);
}
调到了
public void arounddd(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("==============arounddd 前置通知=========");
joinPoint.proceed(); //MethodBeforeAdviceInterceptor去执行,
System.out.println("==============arounddd 后置通知=========");
}
public Object invoke(MethodInvocation mi) throws Throwable {
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );//beforeee()方法执行,
return mi.proceed(); // 被代理类的方法执行,
}
public void beforeee(JoinPoint joinPoint) {
System.out.println("==============beforeee 前置通知=========");
}
public String doSomething(String param) {
System.out.println("==========AnnotationServiceImpl.doSomething=========");
return "==========AnnotationServiceImpl.doSomething";
}
最后执行after:
invokeAdviceMethod(getJoinPointMatch(), null, null);
protected Object invokeAdviceMethodWithGivenArgs(Object[] args) throws Throwable {
try {
ReflectionUtils.makeAccessible(this.aspectJAdviceMethod);
return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs);
}
} public Object invoke(Object obj, Object... args)
{
MethodAccessor ma = methodAccessor; // read volatile
if (ma == null) {
ma = acquireMethodAccessor();
}
return ma.invoke(obj, args);
} public void afterrr(JoinPoint joinPoint) {
System.out.println("==============afterrr 后置通知=========");
}
==============arounddd 前置通知=========
==============beforeee 前置通知=========
==========AnnotationServiceImpl.doSomething=========
==============arounddd 后置通知=========
==============afterrr 后置通知=========
cglib的代理
return proxyFactory.getProxy(this.proxyClassLoader);
public Object getProxy(ClassLoader classLoader) {
try {
Class<?> rootClass = this.advised.getTargetClass(); //advised = ProxyFactory Class<?> proxySuperClass = rootClass; //AnnotationServiceImpl Callback[] callbacks = getCallbacks(rootClass);//[CglibAopProxy$DynamicAdvisedInterceptor@2ce86164,
CglibAopProxy$StaticUnadvisedInterceptor@5e8f9e2d,
CglibAopProxy$SerializableNoOp@51df223b,
CglibAopProxy$StaticDispatcher@fd46303,
CglibAopProxy$AdvisedDispatcher@60d8c0dc,
CglibAopProxy$EqualsInterceptor@4204541c,
CglibAopProxy$HashCodeInterceptor@6a62689d]
Class<?>[] types = new Class<?>[callbacks.length];
for (int x = 0; x < types.length; x++) {
types[x] = callbacks[x].getClass();
}
enhancer.setCallbackFilter(new ProxyCallbackFilter(
this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
enhancer.setCallbackTypes(types);
return createProxyClassAndInstance(enhancer, callbacks);
}
}
调用方法时候:
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
try {
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); //
[ExposeInvocationInterceptor@65aa6596,
AspectJAfterAdvice: advice method [public void afterrr()]; aspect name 'aspectAnnotation',
AspectJAroundAdvice: advice method [public void arounddd() ]; aspect name 'aspectAnnotation',
MethodBeforeAdviceInterceptor@1ce61929]
Object retVal;
if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
retVal = methodProxy.invoke(target, args);
}
else {
// We need to create a method invocation...
retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
}
retVal = processReturnType(proxy, target, method, retVal);
return retVal;
}
}
public Object proceed() throws Throwable {
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
} Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
else {
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
spring 注解aop调用invoke()的更多相关文章
- Spring注解 - AOP 面向切面编程
基本概念: AOP:Aspect Oriented Programming,即面向切面编程 指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式 前置通知(@Before):在目标 ...
- 重新学习Spring注解——AOP
面向切面编程——思想:在一个地方定义通用功能,但是可以通过声明的方式定义这个功能要以何种方式在何处运用,而无须修改受影响的类. 切面:横切关注点可以被模块化为特殊的类. 优点: 1.每个关注点都集中在 ...
- 基于spring注解AOP的异常处理
一.前言 项目刚刚开发的时候,并没有做好充足的准备.开发到一定程度的时候才会想到还有一些问题没有解决.就比如今天我要说的一个问题:异常的处理.写程序的时候一般都会通过try...catch...fin ...
- Spring注解AOP及单元测试junit(6)
2019-03-10/20:19:56 演示:将xml配置方式改为注解方式 静态以及动态代理推荐博客:https://blog.csdn.net/javazejian/article/details/ ...
- spring 注解AOP
aspectAnnotation的切面信息,加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了. 解析annotationSe ...
- spring注解 aop
@Resource(name="as") 为空按类型装配 @autowired 按类型 @quafiler (name="xx") 按名称 spring继承关 ...
- 框架源码系列十:Spring AOP(AOP的核心概念回顾、Spring中AOP的用法、Spring AOP 源码学习)
一.AOP的核心概念回顾 https://docs.spring.io/spring/docs/5.1.3.RELEASE/spring-framework-reference/core.html#a ...
- Spring同一个类中的注解方法调用AOP失效问题总结
public interface XxxService { // a -> b void a(); void b(); } @Slf4j public class XxxServiceImpl ...
- spring注解、aop(二)
使用注解配置spring 1.导入 spring-aop-5.0.6.RELEASE.jar包 2.为主配置文件引入新的命名空间 xmlns:context="http://www.spri ...
随机推荐
- Linux目录结构-下部
第1章 /etc目录 1.1 /etc/inittab 1.1.1 查看当前系统的运行级别 [root@nfsnobody ~]# runlevel N 3##查看系统当前运行级别 后面的数字表示当前 ...
- 码云git常用命令
Git常用操作命令: 1) 远程仓库相关命令 检出仓库:$ git clone git://github.com/jquery/jquery.git 查看远程仓库:$ git remote -v 添加 ...
- RabbitMQ的消息确认ACK机制
1.什么是消息确认ACK. 答:如果在处理消息的过程中,消费者的服务器在处理消息的时候出现异常,那么可能这条正在处理的消息就没有完成消息消费,数据就会丢失.为了确保数据不会丢失,RabbitMQ支持消 ...
- 浏览器关闭后Session真的消失了吗?
今天想和大家分享一个关于Session的话题: 当浏览器关闭时,Session就被销毁了? 我们知道Session是JSP的九大内置对象(也叫隐含对象)中的一个,它的作用是可以保 存当前用户的状态信 ...
- LabVIEW工控二进制数据存储
在文件存储的逻辑上,二进制文件基于值编码,而不是字符编码,其占用空间小,读取/写入速度快,但是译码比较复杂,不利用数据共享.根据具体编码方式的不同,二进制的使用方式也有所不同,如对bmp格式,规定了文 ...
- 帝国CMS标签【操作类型】说明详解
看标签的参数时候,一般最后一个参数是操作类型说明,可是后面写的是:"操作类型说明 具体看操作类型说明", 这个操作类型说明在什么地方看啊 操作类型 说明 操作类型 说明 0 各栏目 ...
- Java的23种设计模式,详细讲解(二)
本人免费整理了Java高级资料,涵盖了Java.Redis.MongoDB.MySQL.Zookeeper.Spring Cloud.Dubbo高并发分布式等教程,一共30G,需要自己领取.传送门:h ...
- LayoutSubviews的调用
1.当view被添加到另一个view上时调用 2.布局子控件时调用 3.屏幕旋转的时候调用 4.当view的尺寸大小改变的时候调用
- WindowServer优化
Windows Server 2016 禁止自动更新 1. 打开cmd,输入sconfig,出现如下图: 2. 输入5回车,在输入m回车,完成关闭自动更新.
- Ubuntu个人使用笔记整理
Ubuntu笔记 Ubuntu使用过程中整理的一些常用或关键操作整理,以备不时之需, 另外自己可以对界面做一些美化,这部分自行百度去配置,我的界面如图 ##################Ubuntu ...