Java Guice:根据实例是否存在于类路径上,是否可以注入实例?
我有一个Guice 3.0模块和一些接口,它们的实现可能会有所不同。我想要的是通过在我的类路径上搜索来实例化和注入一些依赖项 即 所以,若在应用程序的类路径上找到ConcreteImplementationA.class,那个么应该注入它,若ConcreteImplementationB,那个么B 如果我必须为我的接口配置所有可能的绑定,这不是问题 是否可以用Guice实现它?您可以像这样注册:Java Guice:根据实例是否存在于类路径上,是否可以注入实例?,java,dependency-injection,classpath,guice,Java,Dependency Injection,Classpath,Guice,我有一个Guice 3.0模块和一些接口,它们的实现可能会有所不同。我想要的是通过在我的类路径上搜索来实例化和注入一些依赖项 即 所以,若在应用程序的类路径上找到ConcreteImplementationA.class,那个么应该注入它,若ConcreteImplementationB,那个么B 如果我必须为我的接口配置所有可能的绑定,这不是问题 是否可以用Guice实现它?您可以像这样注册: public class MyModule extends AbstractModule {
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();
}
}
公共类MyModule扩展了AbstractModule{
私有静态最终类myInterfaceClass=getMyInterfaceClass();
@抑制警告(“未选中”)
私有静态类getMyInterfaceClass(){
试一试{
return(Class)Class.forName(“具体实现A”);
}catch(classnotfounde异常){
试一试{
return(Class)Class.forName(“具体实现B”);
}捕获(ClassNotFoundException e1){
//句柄未找到任何实现
}
}
}
@提供
MyInterface provideMyInterface(){
返回myInterfaceClass.newInstance();
}
}
在我们进行引导时,将注入器注入MyModule,然后使用injector.getInstance(myInterfaceClass)
而不是.newInstance()。@mlk是的,我同意,这将是改进解决方案的下一步,因为这将允许在MyInterface
实现中注入依赖项。伙计们,谢谢你们的宝贵意见。顺便问一下,你知道一些DI框架可以提供这种开箱即用的功能吗?我的意思是“接口的实现是注入的,可以在类路径上找到”?
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();
}
}