You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过HK2扫描其他依赖库中的@Service类?

关于hk2-inhabitant-generator扫描依赖包类的解决方案

可以让hk2-inhabitant-generator扫描依赖包中标注@Service的类,无需手动绑定即可通过Autoscan特性将其加入DI容器,具体操作如下:

  • 配置插件扫描指定依赖包
    在你的项目pom.xml中修改hk2-inhabitant-generator插件配置,添加对目标依赖包的扫描规则:

    <plugin>
        <groupId>org.glassfish.hk2</groupId>
        <artifactId>hk2-inhabitant-generator</artifactId>
        <version>你的hk2版本号</version>
        <executions>
            <execution>
                <goals>
                    <goal>generate-inhabitants</goal>
                </goals>
                <configuration>
                    <!-- 精准扫描指定依赖包 -->
                    <scanDependencies>
                        <dependency>
                            <groupId>my.dependency</groupId>
                            <artifactId>A</artifactId>
                        </dependency>
                    </scanDependencies>
                    <!-- 若需扫描所有依赖,可替换为:<scanAllDependencies>true</scanAllDependencies> -->
                </configuration>
            </execution>
        </executions>
    </plugin>
    

    该配置会让插件在构建阶段扫描指定依赖包内的类,提取标注@Service的条目并生成META-INF/hk2-locator/default元数据文件。

  • 自定义依赖包需提前生成元数据
    如果依赖包A是你自行开发的,需要在它的pom.xml中也添加hk2-inhabitant-generator插件,让其在构建时自行生成元数据文件。基础配置示例:

    <plugin>
        <groupId>org.glassfish.hk2</groupId>
        <artifactId>hk2-inhabitant-generator</artifactId>
        <version>对应hk2版本</version>
        <executions>
            <execution>
                <goals>
                    <goal>generate-inhabitants</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    

    这样主项目扫描时可直接读取依赖包已生成的元数据,无需重复解析类文件。

  • 验证生效状态
    构建完成后,检查主项目target/classes/META-INF/hk2-locator/default文件,确认其中包含依赖包A中@Service类的条目;运行服务时,hk2的Autoscan特性会自动加载这些元数据,将对应类注入DI容器。

内容的提问来源于stack exchange,提问作者simmaa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:46:01