我有一个 Guice 3.0 模块和一些接口(interface),其实现可能会有所不同。我想要的是通过在我的类路径中搜索它来实例化并注入(inject)一些依赖项。
即
@Inject
private MyInterface instance;
ConcreteImplementationA implements MyInterface {...}
ConcreteImplementationB implements MyInterface {...}
因此,如果在应用程序的类路径中找到了 ConcreteImplementationA.class - 它应该被注入(inject),如果是 ConcreteImplementationB - 那么 B。
如果我必须为我的界面配置所有可能的绑定(bind),这不是问题。
是否可以用 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();
}
}
关于java - Guice:是否可以根据实例是否存在于类路径中来注入(inject)实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33369652/