Spring AOP工具类使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/boom_man/article/details/88977993

Spring中含有工具类 AopProxyUtils

org.springframework.aop.framework.AopProxyUtils

常用方法

获取targetSource对象可以使用 AopProxyUtils.getSingletonTarget

ProceedingJoinPoint joinPoint

Object source=joinPoint.getTarget();

AspectJ @pointcut语法: http://www.cnblogs.com/caoyc/p/5629507.html

//反射工具类

ReflectionUtils.makeAccessible(ctor);

如果不使用AopProxyUtils

Spring Aop中,获取被代理类的工具

/**
     * 获取被代理类的Object
     * @author Monkey
     */
    public Object getTarget(Object proxy) throws Exception {  
        
        if(!AopUtils.isAopProxy(proxy)) {  
            //不是代理对象  
            return proxy;
        }  
          
        if(AopUtils.isJdkDynamicProxy(proxy)) {  
            return getJdkDynamicProxyTargetObject(proxy);  
        } else { //cglib  
            return getCglibProxyTargetObject(proxy);  
        }    
    }
/**
     * CGLIB方式被代理类的获取
     * @author Monkey
     * 
     */
    private Object getCglibProxyTargetObject(Object proxy) throws Exception {  
        Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");  
        h.setAccessible(true);  
        Object dynamicAdvisedInterceptor = h.get(proxy);  
        Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");  
        advised.setAccessible(true);  
        Object target = ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();   
        return target;  
    }
/**
     * JDK动态代理方式被代理类的获取
     * @author Monkey
     * 
     */
    private Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {  
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");  
        h.setAccessible(true);  
        AopProxy aopProxy = (AopProxy) h.get(proxy);  
        Field advised = aopProxy.getClass().getDeclaredField("advised");  
        advised.setAccessible(true);  
        Object target = ((AdvisedSupport)advised.get(aopProxy)).getTargetSource().getTarget();  
        return target;  
    }
展开阅读全文

没有更多推荐了,返回首页