Guice:是否可以根据实例是否存在于类路径中来注入实例?

Guice: Is it possible to inject an instance depending on wether it exists on classpath?

我有一个 Guice 3.0 模块和一些接口,其实现可能会有所不同。我想要的是通过在我的类路径中搜索它来实例化并注入一些依赖项。

@Inject 
private MyInterface instance;

ConcreteImplementationA implements MyInterface {...}

ConcreteImplementationB implements MyInterface {...}

因此,如果在应用程序的类路径中找到 ConcreteImplementationA.class - 它应该被注入,如果是 ConcreteImplementationB - 那么 B.

如果我必须为我的界面配置所有可能的绑定,这不是问题。

可以用Guice实现吗?

您可以这样注册一个custom provider

public class MyModule extends AbstractModule {

    private static final Class<MyInterface> myInterfaceClass = getMyInterfaceClass();

    @SuppressWarnings("unchecked")
    private static Class<MyInterface> getMyInterfaceClass() {
        try {
            return (Class<MyInterface>) Class.forName("ConcreteImplementationA");
        } catch (ClassNotFoundException e) {
            try {
                return (Class<MyInterface>) Class.forName("ConcreteImplementationB");
            } catch (ClassNotFoundException e1) {
                // Handle no implementation found
            }
        }
    }

    @Provides
    MyInterface provideMyInterface() {
        return myInterfaceClass.newInstance();
    }
}