關于cglib或jdk代理的對象無法獲取其注解的問題

背景

同事本想使用applicationContext.getBeansOfType(XXX.class),獲取到所有實現(xiàn)類,獲取實現(xiàn)類的注解建立子類映射關系,構建策略模式,但是獲取到的子類getAnnotation返回為null

同事老工程的代碼,如下,可以獲取到注解

另外一個工程為什么就獲取不到呢???

初步定位問題

  • 老工程獲取的子類只是spring管理的實例化的bean
  • 新工程獲取到的子類是spring的代理對象
  • spring代理對象不可使用getAnnotation獲取注解信息
  • 被代理的類要獲取到目標類方可獲取注解

梳理問題點

  1. 為什么新工程是代理對象,老工程不是呢
  2. 如何獲取被代理對象的目標類
  3. 不獲取被代理對象的目標類,有沒有方法獲取注解

問題解決

為什么新工程是代理對象

  • 新工程使用了aop(比如開啟事務、切面),掃描包路徑過大,導致所使用的的bean被spring代理
    需要合理規(guī)劃包路徑

如何獲取被代理對象的目標類

import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;

import java.lang.reflect.Field;

public class AopTargetUtils {
    /**
     * 獲取 目標對象
     * @param proxy 代理對象
     * @return 目標對象
     * @throws Exception
     */
    public static Object getTarget(Object proxy) throws Exception {
        if (!AopUtils.isAopProxy(proxy)) {
            return proxy;
        }
        if (AopUtils.isJdkDynamicProxy(proxy)) {
            proxy = getJdkDynamicProxyTargetObject(proxy);
        } else {
            proxy = getCglibProxyTargetObject(proxy);
        }
        return getTarget(proxy);
    }

    private static 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;
    }

    private static 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;
    }
}

不獲取被代理對象的目標類,有沒有方法獲取注解,答案是有的,通過AnnotationUtil方式獲取

Order annotation =
 AnnotationUtils.findAnnotation(abstractWordFilter.getClass(), Order.class);
遞歸解決多重代理問題
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容