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

1 背景

在spring boot中,利用ApplicationContext扫描自定义方法注解,可能出现无法获取自定义注解的情况

通过debug得到class文件名含有EnhancerBySpringCGLIB,类似于这样:

在这里插入图片描述
或含有$ProxyXXX,类似于这样:
在这里插入图片描述

2 原因

其根本原因在于,applicationContext.getBeansWithAnnotation(类注解.class) 方法获取Bean时,可能拿到的是GClib代理后的类或者Jdk代理的类,导致 bean.getClass().getDeclaredMethods() 拿不到原真实类的方法

因此需要根据具体情况,判断是何种代理,然后利用反射去获取对应真实类,拿到其方法

3 案例

这里封装了一个自定义方法注解,用于监听MQ消息:

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

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

将注解添加到对应的方法上

    @MqttListener(Topic.TEST)
    public void test(MqttEntity entity) {
        log.info("接收到的数据:{}", entity);
        testSync(entity.getValues());
    }

在项目中新增一个配置类实现CommandLineRunner,实现其run方法,通过ApplicationContext扫描程序中的bean,拿到对应的注解

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

    @Override
    public void run(String... args) throws Exception {
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        Arrays.stream(beanDefinitionNames).forEach(beanName -> {
            Object bean = applicationContext.getBean(beanName);

            Method[] declaredMethods = null;
            //判断是何种类型的代理
            if (AopUtils.isJdkDynamicProxy(bean)){
                Object singletonTarget = AopProxyUtils.getSingletonTarget(bean);
                if (singletonTarget != null) {
                    declaredMethods = singletonTarget.getClass().getDeclaredMethods();
                }
            } else if (AopUtils.isCglibProxy(bean)) {
                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) {
                        // ......执行相应的逻辑
                    }
                }
            }
        });
    }
}

通过这种方式既可解决自定义注解扫描失败的问题,同时自定义注解还可与其他注解实现共存

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值