繁体   English   中英

SPI出现Guice错误

[英]SPI with Guice error

因此,我一直在为Java项目制作某种插件API(以从外部加载JAR文件),而且,我希望能够将任何插件内的任何Guice模块添加到我项目的依赖关系图中。

我所做的是拥有一个PluginsModule,并在configure方法中扫描插件中的其他模块,然后使用Java的ServiceLoader进行安装。

我制作了一个测试插件并为其制作了一个模块,我确认它确实已安装。 此时没有问题。 当我在该模块中执行任何操作时,问题就会出现,例如,我将某个接口绑定到该插件中的实现(只是为了解决这一问题,我在没有该插件的情况下做了同样的事情,并且它起作用了,所以这不是绑定问题)并尝试了要注入它,会出现配置错误,指出该接口没有实现。

public enum StandardGuiceModuleScanningStrategy implements GuiceModuleScanningStrategy {
INSTANCE;

@Override
public Set<Module> scan(Path directory) throws IOException {
    File directoryAsFile = directory.toFile();
    File[] childrenFiles = directoryAsFile.listFiles();

    if (!directoryAsFile.isDirectory()
            || childrenFiles == null
            || childrenFiles.length == 0) {
        return Collections.emptySet();
    }

    Set<Module> modules = new HashSet<>();

    for (File childrenFile : childrenFiles) {
        ClassLoader directoryClassLoader = new URLClassLoader(
                new URL[]{childrenFile.toURI().toURL()});
        ServiceLoader<Module> moduleServiceLoader = ServiceLoader.load(
                Module.class, directoryClassLoader);

        moduleServiceLoader.forEach(modules::add);
    }

    return modules;
}

如前所述,在我的GuiceModuleScanningStrategy的实现中,我确实使用了ServiceLoader。 无论如何,我还尝试了其他方法,例如扫描JAR文件并检查模块,并查看其是否具有特定的注释。

所有带有@GuiceModule注释的Guice模块都将安装到子Injector中。 @AutoBind注释的所有类都将绑定到所有继承的接口。 您也可以命名它,这将导致命名的绑定并覆盖应该使用的接口。 而且,如果您不想使用所有功能,只需覆盖StartupModule并仅绑定所需的功能或您自己的功能即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM