日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

spring boot中動態代理導致自定義注解掃描失敗以及解決辦法

作者:kangaroo. 更新時間: 2022-07-11 編程語言

在spring boot中,自定義方法注解,在有其他注解存在的情況下,可能出現無法獲取自定義注解的情況

利用ApplicationContext掃描時,通過debug得到class文件名含有EnhancerBySpringCGLIB,類似于這樣:

在這里插入圖片描述
或含有$ProxyXXX,類似于這樣:
在這里插入圖片描述

1 原因

其根本原因在于,applicationContext.getBeansWithAnnotation(類注解.class) 方法獲取到的Bean,是GClib代理后的類或者Jdk代理的類,導致 bean.getClass().getDeclaredMethods() 拿不到原真實類的方法

需要根據情況,利用反射去獲取對應真實類,拿到其方法

2 解決方案

這里封裝了兩個注解,用于監聽MQ消息:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MqttClient {
    String value() default "";
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MqttListener {
    /**
     * TOPIC,支持處理多個消息
     *
     * @return
     */
    String[] value() default {};

    /**
     * QOS
     *
     * @return
     */
    int qos() default 0;
}

其中,@MqttClient 類注解,@MqttListener 方法注解

新增一個配置類實現CommandLineRunner,實現其run方法,掃描對應注解的bean

@Component
@Slf4j
public class MqttAnnotationScanner implements CommandLineRunner {
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void run(String... args) throws Exception {
        Map<String, Object> beansMap = applicationContext.getBeansWithAnnotation(MqttClient.class);
        for (Object bean : beansMap.values()) {
            Method[] declaredMethods = null;
            //判斷是否為JdkDynamicProxy代理類
            if (AopUtils.isJdkDynamicProxy(bean)){
                Object singletonTarget = AopProxyUtils.getSingletonTarget(bean);
                if (singletonTarget != null) {
                    declaredMethods = singletonTarget.getClass().getDeclaredMethods();
                }
            } else if (AopUtils.isCglibProxy(bean)) {//判斷是否為CglibProxy代理類
                declaredMethods = bean.getClass().getSuperclass().getDeclaredMethods();
            } else {
                declaredMethods = bean.getClass().getDeclaredMethods();
            }

            if (declaredMethods != null) {
                for (Method method : declaredMethods) {
                    MqttListener annotation = method.getAnnotation(MqttListener.class);
                    if (annotation != null) {
                        // ......執行相應的邏輯
                    }
                }
            }

        }
    }
}

這樣,就可以拿到對應的CGlib代理類的注解方法了,實現與其他注解共存

	@RedisLock(lockKey = "{{#entity.uid}}")
    @MqttListener(Topic.TEST)
    public void test(MqttEntity entity) {
        log.info("接收到的數據:{}", entity);
        testSync(entity.getValues());
    }

原文鏈接:https://blog.csdn.net/Vampire_1122/article/details/125415105

欄目分類
最近更新