簡體   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