Quarkus中如何使用Jandex索引?已配置Maven构建索引却不知用法
如何在Quarkus中高效使用Jandex索引(无需手动声明类)
既然你已经在Maven中配置了Jandex构建插件,完全不需要手动通过Indexer逐个添加类——Quarkus会自动帮你处理索引的生成与加载,直接注入现成的索引实例即可。
1. 直接注入Jandex Index实例
在你的Java类中,通过CDI注入io.quarkus.jandex.Index,就能直接使用构建阶段自动生成的完整索引:
import io.quarkus.jandex.Index; import io.quarkus.jandex.ClassInfo; import jakarta.inject.Inject; import java.util.Collection; public class IndexUsageService { @Inject Index jandexIndex; public void processIndexedClasses() { // 获取所有被索引的类 Collection<ClassInfo> allIndexedClasses = jandexIndex.getKnownClasses(); // 示例:查找带有特定注解的类 Collection<ClassInfo> annotatedClasses = jandexIndex.getKnownClassesWithAnnotation("com.yourpackage.YourCustomAnnotation"); // 其他索引操作... } }
2. 为什么手动Indexer不是最优解?
你当前的手动Indexer方式需要逐个声明要扫描的类,项目类数量增多后会变得极度繁琐。而Maven的Jandex插件会在compile阶段自动扫描target/classes下的所有项目类,生成META-INF/jandex.idx索引文件;Quarkus启动时会自动加载该文件,通过CDI注入就能直接使用完整索引。
3. 确认Maven插件配置正确性
确保你的pom.xml中Jandex插件配置无误,标准配置如下:
<build> <plugins> <plugin> <groupId>org.jboss.jandex</groupId> <artifactId>jandex-maven-plugin</artifactId> <version>3.1.1</version> <executions> <execution> <id>generate-jandex-index</id> <goals> <goal>jandex</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
4. 扩展:扫描第三方依赖类
如果需要扫描第三方依赖中的类,可在插件配置中添加依赖坐标,让Jandex一并处理:
<plugin> <groupId>org.jboss.jandex</groupId> <artifactId>jandex-maven-plugin</artifactId> <version>3.1.1</version> <executions> <execution> <id>generate-jandex-index</id> <goals> <goal>jandex</goal> </goals> <configuration> <includeDependencies> <includeDependency>com.some-vendor:third-party-lib</includeDependency> </includeDependencies> </configuration> </execution> </executions> </plugin>
内容的提问来源于stack exchange,提问作者tomasz-mer
相关产品推荐
相关产品推荐

