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

另外一個工程為什么就獲取不到呢???
初步定位問題
- 老工程獲取的子類只是spring管理的實例化的bean
- 新工程獲取到的子類是spring的代理對象
- spring代理對象不可使用getAnnotation獲取注解信息
- 被代理的類要獲取到目標類方可獲取注解
梳理問題點
- 為什么新工程是代理對象,老工程不是呢
- 如何獲取被代理對象的目標類
- 不獲取被代理對象的目標類,有沒有方法獲取注解
問題解決
為什么新工程是代理對象
- 新工程使用了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);

遞歸解決多重代理問題