栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring boot中动态代理导致自定义注解扫描失败以及解决办法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring boot中动态代理导致自定义注解扫描失败以及解决办法

在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 {
    
    String[] value() default {};

    
    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 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());
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/984406.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号