这是我遇到的问题:
Class SimpleCommand implements Executable{
private final ConfigManager config;
private String name;
@Inject
public SimpleCommand(ConfigManager config, @Assisted String name){
this.config = config;
this.name = name;
}
}
Class MyModule extends AbstractModule{
@Override
protected void configure() {
bind(CommandFactory.class).toProvider(FactoryProvider.newFactory(CommandFactory.class, SimpleCommand.class));
bind(Executable.class).to(SimpleCommand.class);
}
}
当我尝试使用以下方法获取 SimpleCommand 实例时:
Guice.createInjector(new MyModule()).getInstance(CommandFactory.class).create("sample command");
我收到了这个错误:
1) No implementation for java.lang.String annotated with @com.google.inject.assistedinject.Assisted(value=) was bound.
while locating java.lang.String annotated with @com.google.inject.assistedinject.Assisted(value=)
for parameter 2 at model.Command.<init>(SimpleCommand.java:58)
at module.MyModule.configure(MyModule.java:34)
所以我的问题是当 SimpleCommand 具有 Assisted Injected 参数时,如何将 SimpleCommand 绑定到 Executable?
这是 CommandFactory 及其实现:
public interface CommandFactory{
public Command create(String name);
}
public class GuiceCommandFactory implements CommandFactory{
private Provider<ConfigManager> configManager ;
@Inject
public GuiceCommandFactory(Provider<ConfigManager> configManager){
this.configManager = configManager;
}
public Command create(String cmd){
return new Command(configManager.get(), cmd);
}
}