You need to enable JavaScript to run this app. 在Micronaut中如何获取被自定义注解标注的所有类集合?
优惠活动
大模型
产品
解决方案
定价
更多

在Micronaut中如何获取被自定义注解标注的所有类集合?

Micronaut获取标注@Consumed注解类的两种实现方案

方法1:基于Bean Introspection实现

该方案依赖Micronaut编译时生成的Bean内省元数据,无运行时反射,性能高、原生镜像兼容性好。

第一步:修改自定义注解

给@Consumed添加@Introspected元注解,所有标注该注解的类会自动生成内省元数据:

import io.micronaut.core.annotation.Introspected;
import java.lang.annotation.*;

@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Introspected
public @interface Consumed {
}

第二步:获取标注类列表

import io.micronaut.core.beans.BeanIntrospection;
import io.micronaut.core.beans.BeanIntrospector;
import jakarta.inject.Singleton;
import java.util.List;
import java.util.stream.Collectors;

@Singleton
public class ConsumedClassService {
    public List<Class<?>> listConsumedClasses() {
        return BeanIntrospector.SHARED
                .findIntrospections(Consumed.class)
                .stream()
                .map(BeanIntrospection::getBeanType)
                .collect(Collectors.toList());
    }
}

方法2:不使用Bean Introspection实现

该方案基于类路径扫描实现,不需要生成内省元数据:

可选优化(推荐)

给@Consumed添加@Indexed元注解,编译时生成注解索引,大幅提升扫描速度,原生镜像场景下也能正常运行:

import io.micronaut.context.annotation.Indexed;
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Indexed(Consumed.class)
public @interface Consumed {
}

扫描获取标注类列表

import io.micronaut.core.io.scan.ClassPathAnnotationScanner;
import jakarta.inject.Singleton;
import java.util.List;

@Singleton
public class ConsumedClassService {
    public List<Class<?>> listConsumedClasses() {
        // 替换为你存放事件类的根包路径
        String scanBasePackage = "com.your.project.event";
        return new ClassPathAnnotationScanner()
                .scan(Consumed.class, scanBasePackage)
                .collectList()
                .block();
    }
}

内容的提问来源于stack exchange,提问作者Md. Shahariar Hossen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 07:45:08