Spring AOP工具类使用
原创
©著作权归作者所有:来自51CTO博客作者简单美好的原创作品,请联系作者获取转载授权,否则将追究法律责任
Spring中含有工具类 AopProxyUtils
org.springframework.aop.framework.AopProxyUtils
常用方法
获取targetSource对象可以使用 AopProxyUtils.getSingletonTarget
ProceedingJoinPoint joinPoint
Object source=joinPoint.getTarget();
//反射工具类
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;
}