1. import org.springframework.aop.framework.AdvisedSupport;
    2. import org.springframework.aop.framework.AopProxy;
    3. import org.springframework.aop.support.AopUtils;
    4. import java.lang.reflect.Field;
    5. /**
    6. * @author shizi
    7. * @since 2020/10/19 1:45 下午
    8. */
    9. public class SpringTargetBeanUtils {
    10. /**
    11. * 获取 目标对象
    12. *
    13. * @param proxy 代理对象
    14. */
    15. public static Object getTarget(Object proxy) throws Exception {
    16. if (AopUtils.isJdkDynamicProxy(proxy)) {
    17. return getJdkDynamicProxyTargetObject(proxy);
    18. } else if(AopUtils.isCglibProxy(proxy)){
    19. return getCglibProxyTargetObject(proxy);
    20. } else {
    21. return proxy;
    22. }
    23. }
    24. private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
    25. Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
    26. h.setAccessible(true);
    27. Object dynamicAdvisedInterceptor = h.get(proxy);
    28. Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
    29. advised.setAccessible(true);
    30. return ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
    31. }
    32. private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
    33. Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
    34. h.setAccessible(true);
    35. AopProxy aopProxy = (AopProxy) h.get(proxy);
    36. Field advised = aopProxy.getClass().getDeclaredField("advised");
    37. advised.setAccessible(true);
    38. return ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
    39. }
    40. }