每期一个小窍门: 获取全部带有自定义方法注解的类和方法

比如我自定义了MqListener注解
启动时自动加载所有消费者
我就需要获取全部被注解方法
代码如下

  @Override
    public void registConsumer() {
    
    
        String[] beanNames = applicationContext.getBeanDefinitionNames();

        for (String beanName : beanNames) {
    
    
            Class<?> clazz = applicationContext.getType(beanName);
            if (clazz == null) {
    
    
                continue;
            }
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
    
    
                if (method.isAnnotationPresent(MqListener.class)) {
    
    
                    MqListener mqListener = method.getAnnotation(MqListener.class);
                    System.out.println("找到了 方法名:" + method.getName());
                    String topic = mqListener.topic();
                    String groupId = mqListener.groupId();

                    // 初始化 消费者
                    initMqConsumer(topic, groupId, beanName, method);
                }
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_33709508/article/details/132172226