如何在Guice中将类与构造函数绑定



我想将MyImpl绑定到Multibinding。但是MyImpl的构造函数接受参数。

final Multibinder<MyInterface> binder = Multibinder.newSetBinder(binder(), MyInterface.class)
binder.addBinding().to(MyImpl.class);
public MyImpl(Boolean myParam) ...

我不想@Inject,因为它是布尔型的,偶尔可以在其他地方注入。所以。我可以引入一些Enum并注入它,然后如何做到这一点?或者我可以更好地写吗

binder.addBinding().to(MyImpl.class, true);
binder.addBinding().to(MyImpl2.class, false);

还是这样?

我不想@Inject它,因为它是布尔型的,偶尔可以在其他地方注入。若要避免这种情况,请使用"命名注释"。

解决方案一:

@Inject
public TextEditor(@Named("OpenOffice") SpellChecker spellChecker) { ...}

这是绑定代码:

bind(SpellChecker.class).annotatedWith(Names.named("OpenOffice")).to(OpenOfficeWordSpellCheckerImpl.class);

解决方案二:

在模块中加载java属性并使用java道具名称:

private static Properties loadProperties(String name){
Properties properties = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream(name);
try {
properties.load(is);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
if(is != null){
try {
is.close();
} catch (IOException dontCare) { }
}
}
return properties;
}
protected void configure() {
try{
Properties gameProperties = loadProperties("game.properties");
Names.bindProperties(binder(),gameProperties);
}catch (RuntimeException ex){
addError("Could not configure Game Properties");
};
}

最新更新