Spring代理對象導致的獲取不到原生對象注解的解決
問題描述
我在接受 mq 消息的時候,需要做一個重試次數限制,如果超過 maxNum 就發(fā)郵件告警,不再重試。
所以我需要對 consumer 對象進行代理,然后如果超過異常次數,我直接返回成功,并且發(fā)送成功消息,但是我獲取 consumer handler 方法的方式是通過 method.getAnnotation(XXClient.class) 方式,那么就會返回 null。
問題示例代碼
目標類, 我這里就之定義一個 test 方法,里面做一些個簡單的打印。
@Component
public class TestBean {
? ? @Anno
? ? public void test() {
? ? ? ? System.out.println("test .....");
? ? }
}代理邏輯邏輯處理, 主要就是做一個 @Around 的方法覆蓋,保證在調用目標方法之前,先輸出我插入的邏輯。
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Anno {
? ? String key() default "100%";
}
@Aspect
@Component
public class AnnoAspect {
? ? @Around("@annotation(anno)")
? ? public Object anno(ProceedingJoinPoint point, Anno anno) throws Throwable {
? ? ? ? System.out.println("anno invoke!!!!!!");
? ? ? ? return point.proceed();
? ? }
}調用點, 通過 AnnotationConfigApplicationContext 獲取 bean. 然后通過 getMethods() 獲取所有的方法,最后查找 Anno 注解的 Method 對象。
? ? AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanStart.class);
? ? TestBean bean = applicationContext.getBean(TestBean.class);
? ? Class<? extends TestBean> classz = bean.getClass();
? ? Method[] methods = classz.getMethods();
? ? for (Method m : methods) {
? ? ? ? Anno annotation = m.getAnnotation(Anno.class);
? ? ? ? if (annotation != null) {
? ? ? ? ? ? System.out.println(" ============= invoke test ===========");
? ? ? ? ? ? m.invoke(bean, new Object());
? ? ? ? }
? ? } ? ?由于 m.getAnnotaion(Anno.class) 無法獲取到注解信息,所以執(zhí)行 test 方法失敗,
到此問題還原完畢,我們再來看看如何解決。
解決方案
通過 Anno ao = AnnotationUtils.findAnnotation(classz, Anno.class); 方法獲取即可。
有的代碼是這樣寫的 :
String name = classz.getName();
boolean isSpringProxy = name.indexOf("SpringCGLIB$$") >= 0;
Method[] methods;
if (isSpringProxy) {
? ? methods = ReflectionUtils.getAllDeclaredMethods(AopUtils.getTargetClass(bean));
} else {
? ? methods = classz.getMethods();
}
// 省略部分代碼
if (isSpringProxy) {
? ? annotation = AnnotationUtils.findAnnotation(method, MqClient.class);
} else {
? ? annotation = method.getAnnotation(Anno.class);
}這里他會做一個判斷,如果是代理對象就調用 ReflectionUtils.getAllDeclaredMethods 獲取所有的方法, 然后再去拿注解的時候二次判斷一下,如果存在代理,那么就通過 AnnotationUtils.findAnnotation 感覺是相當的嚴謹。
總結
Spring 提供了非常強大的一站式開發(fā)功能,而且還提供了比較優(yōu)秀的工具方法比如: BeanUtils 、ReflectionUtils 、AnnotationUtils 等,這些都是我們值得掌握的基礎工具類。
參考資料
https://www.jianshu.com/p/b69e64121b97
到此這篇關于Spring代理對象導致的獲取不到原生對象注解的解決的文章就介紹到這了,更多相關Spring獲取不到原生對象注解內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring的@Value注入復雜類型(通過@value注入自定義類型)
Spring的@Value可以注入復雜類型嗎?今天教你通過@value注入自定義類型。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
springboot 整合fluent mybatis的過程,看這篇夠了
這篇文章主要介紹了springboot 整合fluent mybatis的過程,配置數據庫連接創(chuàng)建數據庫的詳細代碼,本文給大家介紹的非常詳細,需要的朋友可以參考下2021-08-08
Java EasyExcel讀寫excel如何解決poi讀取大文件內存溢出問題
這篇文章主要介紹了Java EasyExcel讀寫excel如何解決poi讀取大文件內存溢出問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06

