动态查找spring aop的切面方法

2 篇文章 0 订阅

样例代码

pom.xml 中的依赖

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>

代码:

package test.aop;

import org.aspectj.lang.annotation.*;

@Aspect
public class TestAspect {

    @Pointcut("execution(* test.*.AAA.testAAA(..))")
    public void testPointcut() {
    }

    @Before("testPointcut()")
    public void testBefore() {
        System.out.println("In before.");
        doBefore();
    }

    @Before("testPointcut()")
    public void testBefore2() {
        System.out.println("In before2.");
        doBefore2();
    }

    @After("testPointcut()")
    public void testAfter() {
        System.out.println("In after.");
        doAfter();
    }

    @After("testPointcut()")
    public void testAfter2() {
        System.out.println("In after2.");
        doAfter2();
    }

    @AfterReturning("testPointcut()")
    public void testAfterReturn() {
        System.out.println("In after return.");
        doAfterReturn();
    }

    private void doBefore() {
    }

    private void doBefore2() {
    }

    private void doAfter() {
    }

    private void doAfter2() {
    }

    private void doAfterReturn() {
    }

}
package test.aop;

public class AAA {
    public void testAAA() {
        System.out.println("In AAA.");
    }
}
package test.jetty;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import test.aop.AAA;

import javax.servlet.*;
import java.io.IOException;

public class TestFilter4 implements Filter {
    private ApplicationContext context;
    private AAA aaa;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        context = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        aaa = (AAA) context.getBean("aaa");
        aaa.testAAA();
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"
       default-lazy-init="true">

    <aop:aspectj-autoproxy proxy-target-class="true"/>

    <bean class="test.aop.TestAspect"/>

    <bean id="aaa" class="test.aop.AAA"/>

</beans>

index4.html

<head>
<title>Test Server</title>
</head>
<body>
	<h1>Test Server</h1>
</body>
</html>

web.xml

    <filter>
        <filter-name>testFilter4</filter-name>
        <filter-class>test.jetty.TestFilter4</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>testFilter4</filter-name>
        <url-pattern>/index4.html</url-pattern>
    </filter-mapping>

打包成 war包,放到 jetty 中运行,然后访问一下:

curl http://localhost:8080/test/index4.html

输出结果:

In before.
In before2.
In AAA.
In after.
In after2.
In after return.

spring aop 字节码分析

获取 spring aop 动态创建的 class 的字节码,查看 testAAA() 方法:

  public class test.aop.AAA$$EnhancerBySpringCGLIB$$9dc03f17 extends test.aop.AAA implements ...
  ...
  public final void testAAA();
    descriptor: ()V
    flags: ACC_PUBLIC, ACC_FINAL
    Code:
      stack=5, locals=1, args_size=1
         0: aload_0
         1: getfield      #51                 // Field CGLIB$CALLBACK_0:Lorg/springframework/cglib/proxy/MethodInterceptor;
         4: dup
         5: ifnonnull     17
         8: pop
         9: aload_0
        10: invokestatic  #55                 // Method CGLIB$BIND_CALLBACKS:(Ljava/lang/Object;)V
        13: aload_0
        14: getfield      #51                 // Field CGLIB$CALLBACK_0:Lorg/springframework/cglib/proxy/MethodInterceptor;
        17: dup
        18: ifnull        37
        21: aload_0
        22: getstatic     #57                 // Field CGLIB$testAAA$0$Method:Ljava/lang/reflect/Method;
        25: getstatic     #59                 // Field CGLIB$emptyArgs:[Ljava/lang/Object;
        28: getstatic     #61                 // Field CGLIB$testAAA$0$Proxy:Lorg/springframework/cglib/proxy/MethodProxy;
        31: invokeinterface #67,  5           // InterfaceMethod org/springframework/cglib/proxy/MethodInterceptor.intercept:(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;Lorg/springframework/cglib/proxy/MethodProxy;)Ljava/lang/Object;
        36: return
        37: aload_0
        38: invokespecial #49                 // Method test/aop/AAA.testAAA:()V
        41: return
        42: athrow
        43: new           #75                 // class java/lang/reflect/UndeclaredThrowableException
        46: dup_x1
        47: swap
        48: invokespecial #78                 // Method java/lang/reflect/UndeclaredThrowableException."<init>":(Ljava/lang/Throwable;)V
        51: athrow
      Exception table:
         from    to  target type
             0    42    42   Class java/lang/RuntimeException
             0    42    42   Class java/lang/Error
             0    42    43   Class java/lang/Throwable

伪代码:

package test.aop;

public class AAA$$EnhancerBySpringCGLIB$$9dc03f17 extends AAA implements ... {
	...
	public final void testAAA();
		if (CGLIB$CALLBACK_0 == null)
			CGLIB$BIND_CALLBACKS(this);
		if (CGLIB$CALLBACK_0 == null)
			super.testAAA();
		else
			CGLIB$CALLBACK_0.intercept(this, test/aop/AAA.testAAA, CGLIB$testAAA$0$Proxy);
	}
}

可以推断出 spring aop 在动态创建这个类的时候,并没有把 TestAspect 中的切面方法编织进去,而是在运行时进行动态绑定,如果绑定成功,则调用 intercept() 方法进行拦截,并且在适当的地方调用原本的 testAAA() 方法。

做个有趣的实验

修改 TestFilter4 中 doFilter() 的代码:

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        aaa = (AAA) context.getBean("aaa");
        aaa.testAAA();
        System.out.println("Class of aaa: " + aaa.getClass());
        System.out.println("===============");
        try {
            aaa.getClass().newInstance().testAAA();
        } catch (Exception e) {
            e.printStackTrace();
        }
        chain.doFilter(request, response);
    }

重新进行测试,可以看到输出:

In before.
In before2.
In AAA.
In after.
In after2.
In after return.
Class of aaa: class test.aop.AAA$$EnhancerBySpringCGLIB$$178fd57b
===============
In AAA.

证明了即使使用 class AAA$$EnhancerBySpringCGLIB$$178fd57b 来新建对象,但是因为没有经过 spring 的动态绑定,所以实际运行的还是原来的 testAAA() 方法,可以参考伪代码中的条件分支:

if (CGLIB$CALLBACK_0 == null)
	super.testAAA();

heap dump 分析

对 jetty 做个 heap dump
(PS:如何做 heap dump 可以查看:Java heap dump及分析 )

搜索 “EnhancerBySpringCGLIB”, 选中对象(非 class 开头的那项)
heap dump
从之前的字节码分析,可以知道 spring aop 最终是通过调用 CGLIB$CALLBACK_0intercept() 方法来进行切面编织的。

右键菜单查看 CGLIB$CALLBACK_0 对象。
go into callback0
发现有个 advised 属性,类型为:org.springframework.aop.framework.ProxyFactory
go into callback0 (2)
查看 ProxyFactory 会有有趣的发现
ProxyFactory 1
ProxyFactory 2
test.aop.AAA.test() 方法作为 key,就能从 ProxyFactorymethodCache 里面找到对应的 TestAspect 切面方法。

代码实现

根据上面 heap dump 的分析,可以写一个查找类:

package test.aop;


import agent.jvmti.JvmtiUtils;

import java.lang.reflect.Method;
import java.util.*;

public class SpringAopBytecodeMethodFinder {

    public Set<Method> findBytecodeMethods(Method targetMethod, ClassLoader classLoader) {
        Set<Method> rsSet = new HashSet<>();
        doFind(targetMethod, classLoader, rsSet);
        return rsSet;
    }

    private void doFind(Method targetMethod, ClassLoader classLoader, Set<Method> bytecodeMethodSet) {
        try {
            List<?> proxyFactoryList = JvmtiUtils.getInstance().findObjectsByClass(
                    classLoader.loadClass("org.springframework.aop.framework.ProxyFactory"),
                    Integer.MAX_VALUE
            );
            proxyFactoryList.stream()
                    .map(proxyFactory -> getCallbackChain(proxyFactory, targetMethod))
                    .filter(Objects::nonNull)
                    .forEach(chain -> collectBytecodeMethods(chain, bytecodeMethodSet));
        } catch (Exception e) {
        }
    }

    @SuppressWarnings("unchecked")
    private List<Object> getCallbackChain(Object proxyFactory, Method targetMethod) {
        try {
            Map<Method, List<Object>> methodCache = ReflectionUtils.getFieldValue(
                    "methodCache",
                    proxyFactory
            );
            for (Map.Entry entry : methodCache.entrySet()) {
                Method method = ReflectionUtils.getFieldValue("method", entry.getKey());
                if (method.equals(targetMethod)) {
                    return (List<Object>) entry.getValue();
                }
            }
        } catch (Exception e) {
        }
        return null;
    }

    private void collectBytecodeMethods(List<Object> chain, Set<Method> bytecodeMethodSet) {
        for (Object element : chain) {
            if (!findBytecodeMethod(element, bytecodeMethodSet)) {
                try {
                    findBytecodeMethod(
                            ReflectionUtils.getFieldValue("advice", element),
                            bytecodeMethodSet
                    );
                } catch (Exception e) {
                }
            }
        }
    }

    private boolean findBytecodeMethod(Object element, Collection<Method> bytecodeMethods) {
        String methodName = "getAspectJAdviceMethod";
        try {
            if (ReflectionUtils.findFirstMethod(element.getClass(), methodName) != null) {
                Method method = ReflectionUtils.invoke(methodName, element);
                if (method != null) {
                    bytecodeMethods.add(method);
                    return true;
                }
            }
        } catch (Exception e) {
        }
        return false;
    }
}

(PS: 如何查找类的对象,请参考 在heap上查找class的对象实例

测试代码:

package test.aop;

import agent.jvmti.JvmtiUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.lang.reflect.Method;

public class AAATest {
    static {
        JvmtiUtils.getInstance().load("/home/helowken/test_jni/jni_jvmti/libagent_jvmti_JvmtiUtils.so");
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AAA aaa = (AAA) context.getBean("aaa");
        Method method = ReflectionUtils.findFirstMethod(AAA.class, "testAAA");

        System.out.println("======= Result ======");
        printBytecodeMethods(method);
        System.out.println("==================");
        aaa.testAAA();
        System.out.println("==================");
        printBytecodeMethods(method);
    }

    private static void printBytecodeMethods(Method method) {
        new SpringAopBytecodeMethodFinder()
                .findBytecodeMethods(
                        method,
                        Thread.currentThread().getContextClassLoader()
                ).forEach(System.out::println);
    }
}

运行结果:

======= Result ======
==================
In before.
In before2.
In AAA.
In after.
In after2.
In after return.
==================
public void test.aop.TestAspect.testAfterReturn()
public void test.aop.TestAspect.testAfter2()
public void test.aop.TestAspect.testBefore2()
public void test.aop.TestAspect.testAfter()
public void test.aop.TestAspect.testBefore()

Well~~~,在调用 testAAA() 方法之前,methodCache 中没有东西,于是没法查找到对应的切面方法。

查看一下 ProxyFactory 的源码,发现 methodCache 位于 org.springframework.aop.framework.AdvisedSupport 中,而且是个 private 字段,换言之,只要在 AdvicedSupport 中找到调用它 put(key, value) 方法的代码就好。

// org.springframework.aop.framework.AdvisedSupport.java
	public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, Class<?> targetClass) {
		MethodCacheKey cacheKey = new MethodCacheKey(method);
		List<Object> cached = this.methodCache.get(cacheKey);
		if (cached == null) {
			cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
					this, method, targetClass);
			this.methodCache.put(cacheKey, cached);
		}
		return cached;
	}

接下来,修改一下 SpringAopBytecodeMethodFindergetCallbackChain() 方法:

    @SuppressWarnings("unchecked")
    private List<Object> getCallbackChain(Object proxyFactory, Method targetMethod) {
        try {
            Map<Method, List<Object>> methodCache = ReflectionUtils.getFieldValue(
                    "methodCache",
                    proxyFactory
            );
            for (Map.Entry entry : methodCache.entrySet()) {
                Method method = ReflectionUtils.getFieldValue("method", entry.getKey());
                if (method.equals(targetMethod)) {
                    return (List<Object>) entry.getValue();
                }
            }

			// New code for not found in cache
            Object advisorChainFactory = ReflectionUtils.invoke(
                    "getAdvisorChainFactory",
                    proxyFactory
            );
            if (advisorChainFactory != null) {
                Method method = ReflectionUtils.findFirstMethod(
                        advisorChainFactory.getClass(),
                        "getInterceptorsAndDynamicInterceptionAdvice"
                );
                method.setAccessible(true);
                return (List<Object>) method.invoke(advisorChainFactory, proxyFactory, targetMethod, null);
            }
        } catch (Exception e) {
        }
        return null;
    }

重新运行测试,输出结果:

======= Result ======
public void test.aop.TestAspect.testAfterReturn()
public void test.aop.TestAspect.testAfter2()
public void test.aop.TestAspect.testBefore2()
public void test.aop.TestAspect.testAfter()
public void test.aop.TestAspect.testBefore()
==================
In before.
In before2.
In AAA.
In after.
In after2.
In after return.
==================
public void test.aop.TestAspect.testAfterReturn()
public void test.aop.TestAspect.testAfter2()
public void test.aop.TestAspect.testBefore2()
public void test.aop.TestAspect.testAfter()
public void test.aop.TestAspect.testBefore()

注意事项

Spring context 中的 bean 很可能是 lazy-init 的,在调用AAA aaa = (AAA) context.getBean("aaa"); 之前,spring aop 是不会动态创建 class 的,这时候是没办法查找到切面方法的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值